添加 UIButton 的目标添加到 UIView 子类在 UIViewController 上不起作用
我有一个自定义 UIButton 作为子视图添加到 UIView 子类中。在我的 viewController 中,我将自定义 uiview 作为子视图添加到控制器的视图中。然后我尝试向 uibutton 添加一个目标(在 viewWillLoad 内),但选择器从未被调用。
I have a custom UIButton added as subview to a UIView subclass. In my viewController I add the custom uiview as a subview to the controller's view. Then I try to add a target to uibutton (inside viewWillLoad), but the selector is never called.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我只需要将layoutSubviews 中的所有逻辑移至构造函数即可。
I just needed to move all logic that was in layoutSubviews to the constructor.
确保您正在执行以下操作:
这将创建一个按钮,单击该按钮时该按钮将调用buttonTap 方法。
Make sure you're doing something like this:
This will create a button that calls the buttonTap method when it's clicked.
这是自定义视图和视图控制器逻辑
// 自定义视图
// 视图控制器片段
“pushToRunwayViewController”从未被调用
Here is the custom view and the view controller logic
// custom view
// view controller snippet
"pushToRunwayViewController" is never called
不确定您是否自己弄清楚,但是当您将 Target:self 添加到第一个按钮时, self 是您实际的自定义视图,而不是视图控制器。
因此,如果您将 (pushToRunwayViewController) 方法移至 CustomAISView,一切都应该按预期工作。
我希望这有帮助。
罗格
Not sure if you figured out for yourself but when you addTarget:self to your firstButton, self is your actual custom view, not the view controller.
So if you move your (pushToRunwayViewController) method to CustomAISView everything should work as expected.
I hope this helps.
Rog
首先,UIView 与 UIControl 不同。 UIView并不知道具体如何对待不同的用户交互,也没有实现大部分的事件处理方法。
UIControl 会为你做到这一点。它值得注意的子类是 UIButton。尝试从 UIControl 子类化以获取所有事件处理方法。对于更复杂的方式,在 UIView 的子类中子类化另一个 UIControl 但我认为这不是一个好主意。
更多高级事件处理和消息传递请看:
如何添加 UIViewController 作为以编程方式创建的 UIView 中创建的 UIButton 操作的目标?
First, UIView is different from UIControl. UIView does not know specifically how to treat different user interaction and does not implement most of the event handling method.
UIControl does that for you. Its notable subclass is UIButton. Try to subclass from UIControl to get all the methods for event handling. For a more complex way, inside that subclass of UIView subclass another UIControl but i don't think its a good idea.
More a little bit advanced event handling and message passing look at this:
How to add UIViewController as target of UIButton action created in programmatically created UIView?