gpt4 book ai didi

objective-c - 根据标签更改 UIButton 的颜色

转载 作者:行者123 更新时间:2023-11-28 22:42:43 24 4
gpt4 key购买 nike

得到一堆UIButtons,其中一些需要根据情况改变颜色,目前是这样处理的:

UIButton *button;
button = [self.view viewWithTag:positionInArray];
[button setBackgroundColor:[UIColor cyanColor]];
button = [self.view viewWithTag:positionInArray-1];
[button setBackgroundColor:[UIColor cyanColor]];
button = [self.view viewWithTag:positionInArray+3];
[button setBackgroundColor:[UIColor cyanColor]]
button = [self.view viewWithTag:positionInArray+4];
[button setBackgroundColor:[UIColor cyanColor]];

它可以工作,但是将按钮设置为标签的代码会抛出此警告:

“不兼容的指针类型正在使用类型为‘UIView *’的表达式初始化‘UIButton *__strong’”

我将如何正确地执行此操作?

最佳答案

问题是,viewWithTag: 可能会返回 UIView 的任何子类。如果你知道它肯定会返回一个 UIButton,你可以这样转换它:

button = (UIButton *)[self.view viewWithTag:positionInArray];

这将隐藏警告,但当 View 不是按钮时可能会产生意外结果!一个更好的解决方案是检查返回的 UIView 子类是否是 UIButton:

UIView *view = [self.view viewWithTag:positionInArray];
if ([view isKindOfClass:[UIButton class]]) {
button = (UIButton *)view;
[button setBackgroundColor:[UIColor cyanColor]];
} else {
NSLog(@"Ooops, something went wrong! View is not a kind of UIButton.");
}

关于objective-c - 根据标签更改 UIButton 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056157/

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