得到一堆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/