我觉得这很奇怪。所以我有一个 UIView
我想更改 textcolor
全部UILabel
.这是我所做的:
for (UILabel *label in [self subviews]) { // self is the UIView
label.textColor = someColor;
}
当我运行代码时,它崩溃了,像
UIImageView: unrecognized selector setTextColor: sent to instance (some instance)
这样的错误所以看来
label
在快速枚举中其实是一个UIImageView
.顺便说一句,我确实有两个 UIImageView
s 在 UIView *self
.但是,快速枚举不应该只给出UILabel
吗?仅(因为我指定了 UILabel *label
而不是 UIView *label
)?我认为这是问题所在,因为当我编写以下代码时,它可以工作。
for (UILabel *label in [self subviews]) { // self is the UIView
if ([label isKindOfClass:[UILabel class]]) {
label.textColor = someColor;
}
}
所以在这段代码中,当我检查以保证
label
是 UILabel
然后设置它的textcolor
, 所有 UILabel
View 中的 s 正确地改变了它们的颜色。谁能解释我为什么需要
if-statement
仔细检查实例类型?
最佳答案
您的 2 个循环非常不同。第一个假设所有 subview 都是标签,第二个检查每个 subview 以确保它是一个标签。第一个也应该检查。
快速枚举基本上是语法糖,只是普通的for
环形。它不会神奇地过滤或操作您给它枚举的列表。
关于iphone - 快速枚举在objective-c中没有给出正确的对象类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18043971/