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

标签 objective-c ios cocoa-touch uibutton

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

相关文章:

objective-c - __attribute__ ((deprecated)) 不适用于 objective-c 协议(protocol)方法?

ios - 尝试实现 Objective-C 协议(protocol)的 Swift 类因可选方法冲突错误而失败

ios - Collection View 的单元格未显示在行中

ios - 将长字符串插入到 UILabel 中,通过切割由\n 分隔的每个子字符串的尾部

objective-c - @synchronized() 作为 Objective-C 中的单例方法有什么作用?

ios - 弱 self 在 block 内变为零,但我想在 block 内使用 self 对象

objective-c - EXC_BAD_ACCESS 在 segue 期间?

ios - 在 XIB 中连接 UIView 并使用 Story board 中的 View Controller 加载它

iphone - 使用一个委托(delegate)来管理两个 UIActionSheet

ios - ZBAR读取静态UIImage(无相机预览)