gpt4 book ai didi

ios - 在不同的 IBAction 中更改以编程方式创建的 UIButton 的属性

转载 作者:行者123 更新时间:2023-11-28 22:05:49 25 4
gpt4 key购买 nike

我有一种方法可以创建多个 UIButton以编程方式创建实例并将它们定位在 View 中。另一个IBAction需要更改其中一个的背景颜色 UIButton但是当我尝试操作它时被解雇时,它告诉我在 UIView * 类型的对象上找不到属性

按钮是使用以下方法创建的:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
[view addSubview:button];

当我尝试从其他 IBAction 访问它时,例如:

button.backgroundColor = [UIColor blackColor];

它因上述错误而失败。

非常感谢任何帮助。我看到另一个建议创建一个数组作为 IBOutlet 的答案并以这种方式访问​​它,但我想知道是否还有其他方式。

谢谢!

最佳答案

在全局声明这个button并在tag中标识每个按钮,就像或假设这个

 UIButton * button, *button2; // declare in your view controller.h

- (IBAction)butaction:(id)sender; //this is your color change method;

在你的 view 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;

}
}

关于ios - 在不同的 IBAction 中更改以编程方式创建的 UIButton 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009178/

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