从子视图中的UIButton调用UIViewController中的方法 [英] Calling a method in a UIViewController from a UIButton in a subview

查看:169
本文介绍了从子视图中的UIButton调用UIViewController中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍在了解Objective C并使结构正确。

Still learning about Objective C and getting the structure right.

我有一个带有UIViewController的iOS应用程序,它有一个名为doSomething的已定义方法。在我的视图控制器中,我有一个视图,在该视图中有一些我以编程方式创建的UIButton(参见下面的示例,只有一个按钮)。

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).

现在当我按下按钮时我想给我打电话方法doSomething。我目前的方式是这样的:

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];

由于我的目标是nil,它会响应响应者链,直到找到一个名为doSomething的方法。它确实有效,但它确实感觉不对。

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.

我已经开始研究使用@protocol,但并没有真正理解它。我一直在看一些教程,但对我来说还不够清楚。我已经使用了类似于表视图控制器的协议,但是定义一个对我来说是新的。

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?

谢谢!

推荐答案

当你的目标传递给视图控制器和方法时将在该对象上调用。

As your target pass in the view controller and the method will be called on that object.

编辑:

[myButton addTarget:controller 
             action:@selector(doSomething:)
     forControlEvents:UIControlEventTouchUpInside];

假设你有一个名为controller的变量是你的UIViewController。如果您没有对控制器的引用,那么只需将其传递给您的视图。

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:

查看界面:

@property (assign) UIViewController* controller;

查看实施:

@synthesize controller;

控制器:

- (void) viewDidLoad {
    [super viewDidLoad];
    someView.controller = self;
}

这篇关于从子视图中的UIButton调用UIViewController中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆