今天以UISegmentedControl:分段式選單來改變背景的顏色吧
以元件製作分段式選單
以selectedSegmentIndex得知屬性以及所選的項目:
@IBAction func myToggleChanged(_ sender: UISegmentedControl) {
//sender即選單
if sender.selectedSegmentIndex == 0 {
view.backgroundColor = .white
}else if sender.selectedSegmentIndex == 1{
view.backgroundColor = .black
}else if sender.selectedSegmentIndex == 2{
view.backgroundColor = .red
}else if sender.selectedSegmentIndex == 3{
view.backgroundColor = .orange
}else if sender.selectedSegmentIndex == 4{
view.backgroundColor = .yellow
}
印出各個選單相對應的文字:
print(
sender.titleForSegment(
at: sender.selectedSegmentIndex) ?? "no selected")
}
以程式碼製作分段式選單
切換選項時執行動作的方法:
@objc func onChange(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 0{
view.backgroundColor = .green
}else if sender.selectedSegmentIndex == 1{
view.backgroundColor = .blue
}else if sender.selectedSegmentIndex == 2{
view.backgroundColor = .purple
}
建立分段式選單:
let mySegmentedControl = UISegmentedControl(
items: ["green","blue","purple"])
設置預設選擇的選項:
mySegmentedControl.selectedSegmentIndex = 3