viewWithTag与IBOutletCollection一起使用

时间:2013-06-10 14:37:52

标签: ios objective-c

我有一堆视图,每个视图中都有两个完全相同的标签。每个视图中的标签都标记为1和2。

现在我之前没有使用IBOutletCollection并且引用了每个视图(这是不必要的)并且正在获取对视图中标签的引用,如下所示:

l1 = (UILabel*)[_labels4 viewWithTag:1]; //_labels4 is a UIView with 2 labels in it
l2 = (UILabel*)[_labels4 viewWithTag:2];

工作正常,但代码变得臃肿,所以我想开始使用IBOutletCollection所以我可以使用for循环遍历所有视图

所以,当我这样做时,似乎工作正常,除了标签现在变为UIViews而不是UILabels

for(UIView *view in self.labelViews){ //self.labelViews is the collection of UIViews aka _labels4 + others

    UILabel *l1 = (UILabel*)[view viewWithTag:1];
    UILabel *l2 = (UILabel*)[view viewWithTag:2];

    l2.text = @"Reference"; //crash because unrecognised selector 'setText' sent to UIView
}

有没有人知道为什么?您可以查看更详细的代码over here

帮助消除误解:

enter image description here enter image description here

2 个答案:

答案 0 :(得分:0)

在你的self.labelViews中有一个隐藏在那里的UIView不是UILabel

在您发布的代码中,您可以更改以下内容:

@property(强,非原子)IBOutletCollection(UIView)NSArray * labelViews;

应该阅读

@property(强,非原子)IBOutletCollection(UILabel)NSArray * labelViews;

答案 1 :(得分:0)

好的发现了问题,对不起,这里任何人都没有发现。在这个项目的某个地方将视图设置为0,1,2,3等会导致它们被某些东西修改(不知道还有什么,我正在对不属于我自己的项目进行维护)所以将标记设置为随机的900,901 ......似乎解决了这个问题。

相关问题