Swift handle action on segmented control

怎甘沉沦 提交于 2019-12-04 22:18:14

You set your target to fire just when the value change, so if you select the same segment the value will not change and the popover will not display, try to change the event to TouchUpInside, so it will be fired every time you touch inside the segment

segmetedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents:.TouchUpInside) 
Arbitur

You can add the same target for multiple events.

So lets say your segmentedControlValueChanged: looks like this:

func segmentedControlValueChanged(segment: UISegmentedControl) {
    if segment.selectedSegmentIndex == 0 {
    }
    ...
}

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

segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents:.ValueChanged)
segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents:.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)
Dnyaneshwar Shinde
@IBAction func segmentedControlButtonClickAction(_ sender: UISegmentedControl) {
   if sender.selectedSegmentIndex == 0 {
      print("First Segment Select")
   }
   else { 
      print("Second Segment Select")
   }
}
ikbal

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")
    }
}

Swift4 syntax :

segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", for:.touchUpInside)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!