简体   繁体   中英

Swift handle action on segmented control

I have a HMSegmentedControl with 4 segments. When it is selected, it should pop up view. And when the pop up dismissed, and trying to click on same segment index it should again show the pop up. By using following does not have any action on click of same segment index after pop up dissmissed.

segmetedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: UIControlEvents.ValueChanged) 

You can add the same target for multiple events.

So lets say your segmentedControlValueChanged: looks like this:

@objc func segmentedControlValueChanged(_ sender: UISegmentedControl) {
    if sender.selectedSegmentIndex == 0 {
        // value for first index selected here
    }
}

Then you can add targets for more than 1 events to call this function:

segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .valueChanged)
segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .touchUpInside)

Now your function will get called when a value was changed and when the user releases his finger.

with sender, use the sender name sender when you want to access in the action:

segmentControl.addTarget(self, action: #selector(changeWebView(sender:)), for: .valueChanged)

or

addTarget(self, action: #selector(changeWebView), for: .valueChanged)

Swift 5

// add viewController

@IBOutlet var segmentedControl: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()
    segmentedControl.addTarget(self, action: #selector(CommentsViewController.indexChanged(_:)), for: .valueChanged)
}

// using change

@objc func indexChanged(_ sender: UISegmentedControl) {
    if segmentedControl.selectedSegmentIndex == 0 {
        print("Select 0")
    } else if segmentedControl.selectedSegmentIndex == 1 {
        print("Select 1")
    } else if segmentedControl.selectedSegmentIndex == 2 {
        print("Select 2")
    }
}

您将目标设置为仅在值更改时触发,因此如果您选择同一段值不会更改并且不会显示弹出窗口,请尝试将事件更改为 TouchUpInside,因此每次您触摸内部时都会触发它部分

segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .touchUpInside)
@IBAction func segmentedControlButtonClickAction(_ sender: UISegmentedControl) {
   if sender.selectedSegmentIndex == 0 {
      print("First Segment Select")
   }
   else { 
      print("Second Segment Select")
   }
}

Swift4 语法:

segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", for:.touchUpInside)

Drag and drop create an action which is a value type.

在此处输入图片说明

@IBAction func actionSegment(_ sender: Any) {
    let segemnt = sender as! UISegmentedControl
    print(segemnt.selectedSegmentIndex)// 0 , 1

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM