我有一种方法可以编程方式创建多个UIButton
个实例,并将它们放在视图中。另一个IBAction
需要在触发时更改其中一个UIButton
的背景颜色,但是当我尝试操作它时,它会告诉我在UIView *
类型的对象上找不到该属性
按钮使用以下方式创建:
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];
当我尝试从其他IBAction访问它时,如:
button.backgroundColor = [UIColor blackColor];
由于上述错误而失败。
非常感谢任何帮助。我看到另一个答案建议将数组创建为IBOutlet
并以这种方式访问它,但我想知道是否有另一种方式。
谢谢!
答案 0 :(得分:1)
全局声明此button
并识别tag
中的每个按钮,就像或假设这样
UIButton * button, *button2; // declare in your view controller.h
- (IBAction)butaction:(id)sender; //this is your color change method;
在你的视图controller.m中,只要你添加这个按钮
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag=10; //this is important
[self.view addSubview:button];
button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.tag=20; //this is important
[self.view addSubview:button1];
//here ur color change method
- (IBAction) butaction:(UIButton*)sender {
switch (sender.tag)
{
case 10:
[button setBackgroundColor:[UIColor blackColor]];
break;
case 20:
[button1 setBackgroundColor:[UIColor blackColor]];
break;
default:
break;
}
}
答案 1 :(得分:1)
试试这个,这可能会有所帮助
for (int index=1; index<=5; index++) {
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(ButtonClickedFunction:) forControlEvents:UIControlEventTouchUpInside];
button.tag= index;
[view addSubview:button];
};
在IBAction中实现这个
-(IBAction)ButtonClickedFunction:(UIButton *)button{
button.backgroundColor = [UIColor blackColor];
}
注意:在这里我创建了5个按钮但没有设置框架。请根据您的要求设置框架。 感谢