如何为自定义uicontrol和控制器添加触摸事件?
我有一个自定义UIControl有三个子视图。每个子视图这些的,我添加了一个目标:如何为自定义uicontrol和控制器添加触摸事件?
button.addTarget(self, action: #selector(buttonTapped(clickedBtn:)), for: .touchUpInside)
在该函数buttonTapped
,它的一些特殊的动画做一些转换(它模仿了分段控制)。
现在,在ViewController中,这个自定义的UIControl存在于它必须知道什么时候被触摸。我创建了一个@IBAction
函数,用于与自定义UIControl的触摸事件进行交互。
问题是,这是不可能的(据我所知)。如果我向子视图添加目标触摸事件,则父触摸事件不会被调用。要让父视图调用@IBAction
函数,我必须设置所有子视图的setUserInteractiveEnabled to
true`。当我这样做时,子视图的触摸事件功能将不会被调用。
我需要同时调用触摸事件函数。我怎样才能做到这一点?或者解决这个问题的最好方法是什么?
使用代表,在你的ULControl中添加一个协议需要在你的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。 –
是的!这将做到这一点。 :) 做得好 –
你能有* *全定制控件是'IBAction',然后在'.touchUpInside'确定*这*子视图被窃听? – dfd