【问题标题】:How to detect event when user click on selected segment Control in swift?当用户在swift中单击选定的段控件时如何检测事件?
【发布时间】:2021-11-08 11:45:11
【问题描述】:

我正在快速使用UISegmentControl,现在我创建了@IBAction,因此类型为ValueChanged,但是当我单击选定的段时@IBAction 不会调用。所以我尝试了touchUpInside.allEvents,但没有成功。

【问题讨论】:

  • 那是因为你需要: .valueChanged 而不是 .touchUpInside

标签: ios swift uisegmentedcontrol


【解决方案1】:

请试试这个。

  1. 创建@IBIoutlet。

    @IBOutlet var segControl: UISegmentedControl!
    
  2. 初始化值改变事件。

    segControl.addTarget(self, action: #selector(onChanged(_:)), for: .valueChanged)
    
  3. 处理更改事件。

      @objc func onChanged(_ sender: UISegmentedControl) {
         if segControl.selectedSegmentIndex == 0 {
           print("First Segment")
         } else if segControl.selectedSegmentIndex == 1 {
           print("Second Segment")
         } else if segControl.selectedSegmentIndex == 2 {
           print("Third Segment")
         }
    }
    

或使用@IBAction

@IBAction func onsegControl_Click(_ sender: UISegmentedControl) {
   if sender.selectedSegmentIndex == 0 {
     print("First Segment")
   }
   else { 
     print("Second Segment")
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多