从子视图中的 UIButton 调用 UIViewController 中的方法
仍在学习 Objective C 并获得正确的结构。
我有一个带有 UIViewController 的 iOS 应用程序,它有一个名为“doSomething”的已定义方法。在我的视图控制器中,我有一个视图,并在该视图中以编程方式创建了许多 UIButton(请参阅下面的带有一个按钮的示例)。
现在,当我按下按钮时,我想调用我的方法“doSomething”。我目前的做法是这样的:
[myButton addTarget:nil
action:@selector(doSomething:)
forControlEvents:UIControlEventTouchUpInside];
由于我的目标为零,它会沿着响应者链向上,直到找到一个名为“doSomething”的方法。它确实有效,但感觉不太对劲。
我已经开始考虑使用@protocol,但并没有真正理解它。我一直在看一些教程,但对我来说还不够清楚。我使用过类似表视图控制器的协议,但定义一个协议对我来说是新的。
能否为这个具体案例提供一个例子?
谢谢!
Still learning about Objective C and getting the structure right.
I have an iOS App with a UIViewController that has a defined method named "doSomething". In my view controller I have a view and in that view a number of UIButton that I create programmatically (see example below with one button).
Now when I press the button I want to call my method "doSomething". The way I currently do it is like this:
[myButton addTarget:nil
action:@selector(doSomething:)
forControlEvents:UIControlEventTouchUpInside];
Since my target is nil it goes up the responder chain until it finds a method called "doSomething". It works, but it does not really feel right.
I have started to look into using @protocol but not really got my head around it. I have been looking at some tutorials but for me it is not clear enough. I have used protocols like for the table view controllers, but defining one is new for me.
Would it be possible to get an example for this specific case?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的目标传入视图控制器时,将在该对象上调用该方法。
编辑:
假设您有一个名为控制器的变量,它是您的 UIViewController。如果您没有对控制器的引用,则只需将一个引用传递给您的视图即可。
Edit2:
视图接口:
视图实现:
控制器:
As your target pass in the view controller and the method will be called on that object.
Edit:
Assuming that you have a variable called controller that is your UIViewController. If you don't have a reference to your controller then simply pass one to your view.
Edit2:
View interface:
View implementation:
Controller:
我的方法是将
addTarget
的值设置为self
。这将在添加目标的对象上查找方法
doSomething
。在本例中,这将是视图控制器。The way I'd do it is set the value of
addTarget
toself
.This will look for the method
doSomething
on the object that the target is added in. In this case, this would be the view controller.