【问题标题】:How to add touch event for custom uicontrol and controller?如何为自定义 uicontrol 和控制器添加触摸事件?
【发布时间】:2017-09-10 21:50:51
【问题描述】:

我有一个具有三个子视图的自定义 UIControl。每个子视图,我添加一个目标:

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

在那个函数buttonTapped中,它会做一些特殊的动画来做一些过渡(它模仿分段控制)。

现在,在这个自定义 UIControl 所在的 ViewController 中,必须知道它何时被触摸。我为自定义 UIControl 创建了一个与触摸事件交互的 @IBAction 函数。

问题是,这是不可能的(据我所知)。如果我将目标触摸事件添加到子视图,则不会调用父触摸事件。要让父视图调用@IBAction 函数,我必须设置所有子视图的 setUserInteractiveEnabledtotrue`。当我这样做时,不会调用子视图的触摸事件函数。

我需要调用两个触摸事件函数。我怎样才能做到这一点?或者解决这个问题的最佳方法是什么?

【问题讨论】:

  • 能否将整个自定义控件设为IBAction,然后在.touchUpInside中确定哪个子视图被点击了?

标签: ios swift cocoa-touch uicontrol


【解决方案1】:

使用委托,在 UIControl 中添加一个需要在 ViewController 中实现的协议

通过这种方式,您可以检测是否单击了 UIControl 中的按钮并调用 VC 中的特定函数。

例如:

//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
  }
}

【讨论】:

  • 成功了!我唯一需要添加的是在YourViewController 中,在viewDidLoad 中,您需要将YourUIControl 委托设置为self。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多