Swift handle action on segmented control

拜拜、爱过 提交于 2019-12-06 16:36:38

问题


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) 

回答1:


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) 



回答2:


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.




回答3:


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)



回答4:


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



回答5:


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



回答6:


Swift4 syntax :

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


来源:https://stackoverflow.com/questions/30545198/swift-handle-action-on-segmented-control

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