Segmented Control Tutorial in iOS8 with Swift
- Open Xcode and create a new Single View Application. For product name, use SegmentedControl and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.
- Drag a Segmented Control to the main view.
- Copy and paste this code to your .swift file and Run.
import UIKitimport Foundation
class SegmentController : UIViewController { @IBOutlet var segmentedController:UISegmentedControl! override func viewDidLoad() { [self .setBackgroundColor(0)] }
@IBAction func segmentValueChange (sender : UISegmentedControl) { let selectedIndex = sender.selectedSegmentIndex [self .setBackgroundColor(selectedIndex)] }
func setBackgroundColor (value : Int) { if (value == 0) { // Red self.view.backgroundColor = UIColor.redColor() } else if (value == 1) { //Green self.view.backgroundColor = UIColor.greenColor() } else { // BLue self.view.backgroundColor = UIColor.blueColor() } segmentedController.tintColor = self.view.backgroundColor segmentedController.backgroundColor = UIColor.whiteColor() segmentedController.layer.borderColor = UIColor.whiteColor().CGColor segmentedController.layer.borderWidth = 2 segmentedController.layer.cornerRadius = segmentedController.frame.size.height/2 segmentedController.clipsToBounds = true } }