您可以将选择器指向任何目标 - 通常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
IBAction 让您告诉 Interface Builder 方法实现可以通过您的 xib/storyboard 连接。