How to add touch event for custom uicontrol and controller?

旧巷老猫 提交于 2020-01-01 19:26:11

问题


I have a custom UIControl that has three subviews. Each of those subviews, I add a target:

button.addTarget(self, action: #selector(buttonTapped(clickedBtn:)), for: .touchUpInside)

Within that function buttonTapped, it does some special animations to do some transitions (It mimics the segmented control).

Now, within the ViewController that this custom UIControl exists in must know when it's touched. I created an @IBAction function that interacts with the touch events for the custom UIControl.

The problem is, that isn't possible (as far as I know). If I add a target touch event to the subviews, the parent touch events won't get called. To have the parent view called the @IBAction function, I must set all the subview's setUserInteractiveEnabledtotrue`. When I do that, the subview's touch event functions won't get called.

I need both touch event functions to be called. How can I do this? Or what's the best way to get around this?


回答1:


Use delegates, add a protocol in your UIControl that needs to be implemented in your ViewController.

This way you can detect if a button is clicked in your UIControl and invoke a specific function in your VC.

For Example:

//YourUIControl.Swift
protocol YourUIControlDelegate {
  func didTapFirstButton()
}

class YourUiControl : UIView { //I'm assuming you create your UIControl from UIView

  var delegate : YourUIControlDelegate?
  //other codes here
  .
  .
  .
  @IBAction func tapFirstButton(_ sender: AnyObject) {
     if let d = self.delegate {
       d.didTapFirstButton()
     }
  }
}

//YourViewController.Swift
extension YourViewController : UIControlDelegate {
  func didTapFirstButton() {
     //handle first button tap here
  }
}


来源:https://stackoverflow.com/questions/46145900/how-to-add-touch-event-for-custom-uicontrol-and-controller

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