为什么会这样?
我已经看过关于此问题的帖子here,但我已经在考虑按钮是在不同的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];
谢谢!
答案 0 :(得分:2)
你有拼写错误,在分配和创建按钮bt2之后,你要为bt1设置所有内容
答案 1 :(得分:1)
代码没有错。您可能想要更改的唯一方法是,您要将bt1
的属性(标题和目标)设置两次,而不是为bt2
设置属性。
答案 2 :(得分: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];
}
编译器会为您捕获错误。