简体   繁体   中英

Adding multiple UIButtons to the same UIView only shows the last added button?

Why is this?

I've already seen a post about this issue here , but I'm already considering that the button is to be created in a different x/y position.

Here's what I'm doing:

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];

Thank you!

您在这里有错字,在分配和创建按钮bt2之后,您要为bt1设置所有内容

There is nothing wrong in the code. The only thing you might want to change is, you are setting the properties(title and target) of bt1 two times and you are not setting those for bt2 .

Dead simple way to prevent this from happening with local variables in the same scope: Use another scope.

{
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];
}

The compiler will catch the error for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM