gpt4 book ai didi

ios - 了解 uibutton 目标 self 监督

转载 作者:行者123 更新时间:2023-11-28 18:31:58 26 4
gpt4 key购买 nike

谁能给我解释一下这个例子中的 uibutton 目标功能:

我有一个 ViewController。我向这个 View Controller 添加了一个带有两个按钮的 uiview。一个按钮是在 init 中创建的,另一个是通过“addSecondButton”方法创建的。这两个按钮对 [self superview] 目标(即 ViewController)具有相同的操作。代码:

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 会执行。当按下在 init 之后添加的红色按钮时,应用程序崩溃并显示警告 - uiview 的未知选择器。

我真正不明白的是,当我在 init 中使用 NSLog [self superview] 时,它是 null,因为对象尚未创建并返回到 superview,但由于某种原因确实执行了操作。

感谢您的帮助!

最佳答案

您确实在 initWithFrameMethod 中为蓝色按钮添加了一个 nil 目标。根据 Apple 的 Event Handling Guide ,当您添加一个 nil 目标时,消息(在您的情况下为 specialMethod )将通过响应链传递:

When the user manipulates a control, such as a button or switch, and the target for the action method is nil, the message is sent through a chain of responders starting with the control view.

由于您的 ViewController 是响应链的一部分,它将接收此消息并调用其 specialMethod

关于ios - 了解 uibutton 目标 self 监督,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26947175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com