12

I have been playing with the UISegmentedControl and want to manage it as needed. I've created it on the storyboard, hooked up the outlet and the action. It visualizes fine and the callback on the action indexchanged works. I want to do some other management of this prior to visualization so I am stuck on how to properly access the mysegmentedControl I setup in the storyboard. Seems like a silly question but I could not find a Swift example for the UISegmentedControl that I could relate to currently.

class ViewController: UIViewController, MKMapViewDelegate {
    ...
    //playing around with a Segmented Control
    @IBOutlet var mysegmentedControl : UISegmentedControl

    // Any time the button is clicked in the Segmented Control the index changes so we catch it to do something.

    @IBAction func indexChanged(sender : UISegmentedControl) {
        // This all works fine and it prints out the value of 3 on any click 
        println("# of Segments = \(sender.numberOfSegments)")

        switch sender.selectedSegmentIndex {
        case 0:
            println("first segement clicked")
        case 1:
            println("second segment clicked")
        case 2:
            println("third segemnet clicked")
        default:
            break;
        }  //Switch
    } // indexChanged for the Segmented Control

    override func viewDidLoad() {
        super.viewDidLoad()

         //  1.  How do I get proper access to the mysegmentedControl that was created in the storyboard and is already displayed.
         //      The indexChanged function gets called fine on the display via sender getting passed to it.
         //      I equate this to getting the pointer to it in C so I leverage it elsewhere
         //  2.  Guessing I don't need to init a new UISegmentedControl or do I?

         // This compiles but crashes on run with: fatal error: Can't unwrap 
         println("# of Segments = \(mysegmentedControl.numberOfSegments)")

    } // viewDidLoad    

} // ViewController
Kokanee
  • 975
  • 4
  • 9
  • 20

4 Answers4

15

Here is what i've used and is working fine for me -

@IBOutlet var mysegmentedControl : UISegmentedControl?

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func indexChanged(sender : UISegmentedControl) {
    // This all works fine and it prints out the value of 3 on any click
    println("# of Segments = \(sender.numberOfSegments)")

    switch sender.selectedSegmentIndex {
    case 0:
        println("first segement clicked")
    case 1:
        println("second segment clicked")
    case 2:
        println("third segemnet clicked")
    default:
        break;
    }  //Switch
} // indexChanged for the Segmented Control

override func viewDidLoad() {
    super.viewDidLoad()
    println("# of Segments = \(mysegmentedControl?.numberOfSegments)")

}
Avi
  • 2,196
  • 18
  • 18
  • 1
    ok..tks for running the code. Since it worked in your environment and not mine I stepped back to the storyboard and found one an outlet not configured so once I took care of that then I had access to mysegementedControl (it was no longer nil). I wish Xcode would somehow catch these conditions as I have been caught before with Storyboard misconfigs and it;s a bit tedious to sort them out. Credit given for your help. – Kokanee Jul 25 '14 at 14:42
1

Please find the below code snippet for accessing the uisegmentedcontrol using swift.

   @IBOutlet weak var segmentedControl: UISegmentedControl!
    
    @IBOutlet weak var textLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        textLabel.text = "First Segment Selected";
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func segmentedControlAction(sender: AnyObject) {
        
        if(segmentedControl.selectedSegmentIndex == 0)
        {
            textLabel.text = "First Segment Selected";
        }
        else if(segmentedControl.selectedSegmentIndex == 1)
        {
            textLabel.text = "Second Segment Selected";
        }
        else if(segmentedControl.selectedSegmentIndex == 2)
        {
            textLabel.text = "Third Segment Selected";
        }
    }

if need detail explanation please refer the below link.

https://sourcefreeze.com/uisegmentedcontrol-example-using-swift-in-ios/

Bharathi Devarasu
  • 7,759
  • 2
  • 18
  • 23
0

I'm able to compile and run your code successfully. Your issue is not your segmented ctrl, probably one of your optional object is nil and hence you cannot unwrap it. Have a look at your optional objects.

Also, try @IBOutlet var mysegmentedControl : UISegmentedControl?

This should definitely solve your problem

Avi
  • 2,196
  • 18
  • 18
  • I am not sure what you mean by optional object but it is indeed nil as I put in a check for it now so the question remains how do I get access to the UISegmentedControl that is being used. – Kokanee Jul 24 '14 at 20:07
  • The mysegmentedControl is definitely nil within viewDiDLoad as I wrapped some checks around that. This is the core of the problem as I don't know how to get handle to it since I did not init it and was leveraging the outlet. I can't use your syntax as then the properties are not available like, numberOfSegments – Kokanee Jul 24 '14 at 20:28
0

This is how the IBOutlet should be declared. In fact, Xcode 6 Beta 4 does this automatically for all IBOutlets. The ! marks the variable as an Implicitly Unwrapped Optional:

@IBOutlet var mysegmentedControl : UISegmentedControl!

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html

Read the "Implicitly Unwrapped Optional Type" section.

Shan
  • 3,057
  • 4
  • 21
  • 33
  • Tks Shan - I must have an older version...version Version 6.0 (6A215l). I added the ! and no problems compiling. – Kokanee Jul 25 '14 at 14:43