I have segmented control, and container view, now how can i make 2 views and segmented control needs to switch that 2 views in container view?
I can't find any tutorial for swift or obj c.
I have segmented control, and container view, now how can i make 2 views and segmented control needs to switch that 2 views in container view?
I can't find any tutorial for swift or obj c.
Firstly, go into the container view's View Controller and make sure your two views are variables, either via Interface Builder or Code.
Let's say you called them view1
and view2
.
In your viewDidLoad()
write (swift):
NSNotificationCenter.defaultCenter().addObserver(self, selector: "segmentedControlTapped:", name: "SCTapped", object: nil)
Then, make a new function like this:
func segmentedControlTapped(notif: NSNotification){
let index = notif.userInfo["index"] as Int
if index == 0{
view1.hidden = false
view2.hidden = true
}
else if index == 1{
view1.hidden = true
view2.hidden = false
}
}
Then, in the View Controller housing your Segmented Control, hook up an IBAction (if using IB) to the Control's ValueChanged
action or use code.
The IBAction func should look like this:
@IBAction func tapped(sender: UISegmentedControl){
NSNotificationCenter.defaultCenter().postNotificationName("SCTapped", object: nil, userInfo: ["index": sender.selectedSegmentIndex])
}
What this should do, is when the SC is tapped, it will call the tapped function, which tells the NSNotificationCenter to post a message. This should be received by the VC with the views in it and segmentedControlTapped() should be called, and it will switch your views.