【发布时间】:2014-11-15 15:02:35
【问题描述】:
有人可以向我解释一下这个例子中的 uibutton 目标功能吗:
我有一个 ViewController。我向这个视图控制器添加了一个带有两个按钮的 uiview。一个按钮是在 init 中创建的,另一个是由方法“addSecondButton”创建的。两个按钮在 ViewController 的 [self superview] 目标上具有相同的操作。代码:
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
MySpecialView *myspecialview = [[MySpecialView alloc] initWithFrame:self.view.frame];
[self.view addSubview:myspecialview];
[myspecialview addSecondButton];
}
- (void)specialMethod { NSLog(@"right here!"); }
MySpecialView.m
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 30, frame.size.width, 50)];
[button addTarget:[self superview] action:@selector(specialMethod) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor blueColor];
[self addSubview:button];
}
return self;
}
- (void)addSecondButton {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 90, self.frame.size.width, 50)];
[button addTarget:[self superview] action:@selector(specialMethod) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor redColor];
[self addSubview:button];
}
因此,当点击在 init 中创建的蓝色按钮时,specialMethod 会执行。当按下初始化后添加的红色按钮时,应用程序崩溃并显示警告 - uiview 的未知选择器。
我真正不明白的是,当我在 init 中 NSLog [self superview] 时,它为 null,因为尚未创建对象并返回到 superview,但由于某种原因,该操作确实被执行了。
感谢您的帮助!
【问题讨论】:
-
你确定蓝色按钮的动作被执行了吗?它不应该作为您添加的目标是
nil。 -
100% 确定。创建一个项目,粘贴代码并自己尝试。奇怪的东西他...
标签: ios objective-c uiview uibutton