假设我有一个如下所示的 View 层次结构:
-- > UIViewController (myViewController)
---- > UIView (IBDesignable - myCustomView)
------- > UIButton (myButton)
有没有办法告诉 myViewController
myButton
已被用户交互触发,例如 .touchUpInside
, "没有“使用 Swift
或 Objective C
的委托(delegate)模式?
请注意 myCustomView
是一个 IBDesignable。
最佳答案
例如,使用 IBOutlet
在您的 viewController 上声明 UIButton
变量。
@IBOutlet weak var button: UIButton!
你可以只使用目标 - Action 模式。只需将其添加到您的 viewController 中即可。
button.addTarget(self, action: #selector(handleButtonTouch(_:)), for: .touchUpInside)
并在 viewController 上声明你的函数
func handleButtonTouch(_ button: UIButton) {
print("button has been pressed")
}
编辑
您还可以直接从 Interface Builder 声明一个 IBAction
函数。
单击您的 UIButton
实例,按住键盘上的 CTRL
键,然后将其拖到您的 UIViewController
子类中。
可设置的属性:
Connection: Action Name: function name, something like `handleButtonTouch` Type: UIButton Event: the event you would like the function to be fired, in your case it is `Touch Up Inside`
关于ios - 将 IBDesignable 中的操作 UIButton 转发给父 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41698882/