David David - 3 months ago 15
Swift Question

Not able to use UISegmentedControl with three tabs and ContainerView

I made an iOS app with Xcode and Swift. I want to use UISegmentedControl with three tabs. With these tabs I can switch between three ContainerViews.

Which numbers do I have to input in the alpha fields? 0, 1 and 2? Because when I set 2 it always reverts back to 1. Why that? How can I do this?

This is the code I'm using to connect the tabs with the ContainerViews:

@IBAction func switchSegmentedControll(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0 {
UIView.animateWithDuration(0.5, animations: {
self.segmentedControllFirst.alpha = 1
self.segmentedControllSecond.alpha = 0
// self.segmentedControllThird.alpha = 0
})
} else {
UIView.animateWithDuration(0.5, animations: {
self.segmentedControllFirst.alpha = 0
self.segmentedControllSecond.alpha = 1
// self.segmentedControllThird.alpha = 1
})
}
}

Answer

I think I just found the solution. It was a misunderstanding by myself. I didn't know what Alpha is and how the code I'm using works.

This is the working code:

@IBAction func switchSegmentedControll(sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        UIView.animateWithDuration(0.5, animations: {
            self.segmentedControllFirst.alpha = 1
            self.segmentedControllSecond.alpha = 0
            self.segmentedControllThird.alpha = 0
        })
    } else if sender.selectedSegmentIndex == 1 {
        UIView.animateWithDuration(0.5, animations: {
            self.segmentedControllFirst.alpha = 0
            self.segmentedControllSecond.alpha = 1
            self.segmentedControllThird.alpha = 0
        })
    } else {
        UIView.animateWithDuration(0.5, animations: {
            self.segmentedControllFirst.alpha = 0
            self.segmentedControllSecond.alpha = 0
            self.segmentedControllThird.alpha = 1
        })
    }
}