This is a memorandum of the parts that are prone to mistakes when using Segmented Control.
Completed form
Declaration of each part
ViewController.swift
@IBOutlet weak var selectSegmentedControl: UISegmentedControl!
@IBOutlet weak var DisplayLabel: UILabel!
Add action
ViewController.swift
@IBAction func tappedSegmentedControl(_ sender: UISegmentedControl) {
}
Write the process with a switch statement in the action.
ViewConroller.swift
switch sender.selectedSegmentIndex {
case 0:
print("Selected: iOS")
self.DisplayLabel.text = "iOS"
case 1:
print("Selected: iPadOS")
self.DisplayLabel.text = "iPadOS"
case 2:
print("Selected: watchOS")
self.DisplayLabel.text = "watchOS"
case 3:
print("Selected: tvOS")
self.DisplayLabel.text = "tvOS"
case 4:
print("Selected: macOS")
self.DisplayLabel.text = "macOS"
default:
print("Selected: Not selected")
self.DisplayLabel.text = "Unselected"
}
Whole code
ViewConroller.swift
@IBOutlet weak var selectSegmentedControl: UISegmentedControl!
@IBOutlet weak var DisplayLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.DisplayLabel.text = "Unselected"
}
@IBAction func tappedSegmentedControl(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
print("Selected: iOS")
self.DisplayLabel.text = "iOS"
case 1:
print("Selected: iPadOS")
self.DisplayLabel.text = "iPadOS"
case 2:
print("Selected: watchOS")
self.DisplayLabel.text = "watchOS"
case 3:
print("Selected: tvOS")
self.DisplayLabel.text = "tvOS"
case 4:
print("Selected: macOS")
self.DisplayLabel.text = "macOS"
default:
print("Selected: Not selected")
self.DisplayLabel.text = "Unselected"
}
}
Associate Outlet and Action.
If you say "Because it's always Touch Up Inside" and associate it with Touch Up Inside **, it won't work! ** ** Let's firmly connect ** Value Changed and **.
https://github.com/rea-sna/SegmentedControl_Sample
Thank you for watching until the end ☺︎
Recommended Posts