0

为什么是这样?

我已经在这里看到了关于这个问题的帖子,但我已经在考虑将按钮创建在不同的 x/y 位置。

这就是我正在做的事情:

UIButton * bt1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
bt1.frame = CGRectMake(40, 40, 20, 20);

[bt1 setTitle:@"A" forState:UIControlStateNormal];
[bt1 addTarget:self action:@selector(buttonPushed) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt1];

UIButton * bt2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
bt2.frame = CGRectMake(80, 80, 20, 20);

[bt1 setTitle:@"B" forState:UIControlStateNormal];
[bt1 addTarget:self action:@selector(buttonPushed) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt2];

谢谢!

4

3 回答 3

2

你有错字,在分配和创建按钮 bt2 之后,你正在为 bt1 设置所有东西

于 2013-06-20T18:44:09.313 回答
1

代码没有错。您可能想要更改的唯一一件事是,您设置了bt1两次的属性(标题和目标),而不是为bt2.

于 2013-06-20T18:50:35.743 回答
1

防止在同一范围内的局部变量发生这种情况的简单方法:使用另一个范围。

{
UIButton * bt1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
bt1.frame = CGRectMake(40, 40, 20, 20);

[bt1 setTitle:@"A" forState:UIControlStateNormal];
[bt1 addTarget:self action:@selector(buttonPushed) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt1];
}

{
UIButton * bt2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
bt2.frame = CGRectMake(80, 80, 20, 20);

[bt1 setTitle:@"B" forState:UIControlStateNormal];
[bt1 addTarget:self action:@selector(buttonPushed) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:bt2];
}

编译器将为您捕获错误。

于 2013-06-20T19:25:33.890 回答