C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For a Segmented Control, we usually set the "segments" in Xcode. But they can be set in Swift code.
Names: Provide names for the Segmented Control and the Label. I used "simpleSegmented" and "simpleLabel."
Action: Next, please right click on the Segmented Control, and drag the "Primary Action Triggered" circle to your device screen.
And: Call the Primary Action Triggered func something like "actionTriggered." It is easy to remember.
Example ViewController: Swift
//
// ViewController.swift
// ExampleTime13
//
// ...
//
import UIKit
class ViewController: UIViewController {
// Outlets.
@IBOutlet weak var simpleSegmented: UISegmentedControl!
@IBOutlet weak var simpleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
// Segment action func.
@IBAction func actionTriggered(sender: AnyObject) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
So: Whenever a button in the UISegmentedControl is tapped, actionTriggered will run and change the UILabel's text.
Example func, uses selectedSegmentIndex: Swift
//
// ViewController.swift
// ExampleTime13
//
// ...
//
import UIKit
class ViewController: UIViewController {
// Outlets.
@IBOutlet weak var simpleSegmented: UISegmentedControl!
@IBOutlet weak var simpleLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
// Segment action func.
@IBAction func actionTriggered(sender: AnyObject) {
// The index of the selected segment.
let index = simpleSegmented.selectedSegmentIndex
// Total segment count.
let total = simpleSegmented.numberOfSegments
// Set label.
simpleLabel.text = "Index: \(index) of \(total)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Here: I use 2 segments. One has title "Cat" and the other "Dog." So we can decide whether a user is a cat or dog person.
Result: The UILabel is changed whenever a click (or tap) occurs. It reads out the selected segment's index (starting at 0).