什么时候按钮(UIButton)的目标不是"自我"?

Spe*_*ine 2 iphone action uibutton uiviewcontroller ios

我是iOS的初学者,在编程教程中,以编程方式添加按钮时,target始终设置为self,并且在创建它的控制器中,IBAction会写入action().或者通过界面构建​​器,将target设置为File的Owner.

我的问题是,在什么情况下(一个例子会很棒)目标不是自我.

我能想到的一个场景是,当在一个类(不是a ViewController)方法中根据条件创建一个按钮时,因为该类不是a ViewController,在初始化该类的对象时,ViewController将设置对当前的引用并且它将用作目标,如果出现按钮,则为该按钮定义动作.

Ala*_*ino 6

您可以将选择器定向到任何目标 - 通常self是目标的原因是因为在代码中实例化UIButton/UIBarButtonItem是很正常的,所以很多教程都包括选择器在同一个类中引用的实现.

例如,您可以创建一个类,在View Controller中实例化时,该类仅用于处理这些按钮调用操作:

#import <UIKit/UIKit.h>
#import "OtherObject.h"

@interface SomeViewController : UIViewController

@property (strong, nonatomic) OtherObject *other;

@end

@implementation SomeViewController

@synthesize other;

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *someButton = [[UIButton alloc] initWithFrame:CGRectZero];
    [someButton addTarget:other action:@selector(someMethodInOther) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:someButton];

    UIButton *anotherButton = [[UIButton alloc] initWithFrame:CGRectZero];
    [anotherButton addTarget:other action:@selector(anotherMethodInOther) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:anotherButton];
}

@end
Run Code Online (Sandbox Code Playgroud)

通过IBAction,您可以告诉Interface Builder可以通过xib/storyboard连接方法实现.