【问题标题】:When is target of a button (UIButton) not "self"?什么时候按钮(UIButton)的目标不是“自我”?
【发布时间】:2012-07-09 06:21:36
【问题描述】:
我是 iOS 的初学者,在编程教程中以编程方式添加按钮时,目标始终设置为 self,并且在创建它的那个控制器中,编写了一个动作 (IBAction)。或者通过界面生成器,将目标设置为文件的所有者。
我的问题是,在什么情况下(一个例子会很好)目标不是自我。
我能想到的一个场景是,在一个类的(不是ViewController)方法中,在初始化该类的对象时,会根据条件创建一个按钮,因为该类不是ViewController ,将设置对当前ViewController 的引用,并将其用作为按钮定义操作的目标(如果出现)。
【问题讨论】:
标签:
iphone
ios
uiviewcontroller
uibutton
action
【解决方案1】:
您可以将选择器指向任何目标 - 通常self 是目标的原因是因为在代码中实例化 UIButton/UIBarButtonItem 是很正常的,所以很多教程都包含选择器引用的实现同一个班级。
例如,您可以创建一个类,在您的视图控制器中实例化时,该类旨在仅处理这些按钮调用操作:
#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
IBAction 让您告诉 Interface Builder 方法实现可以通过您的 xib/storyboard 连接。