1

我为我的自定义创建了一个 xib 文件,UIView并将我的 xib 加载到我的自定义UIView中;

NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"ProductDetailView" owner:self options:nil];
self = [views objectAtIndex:0];

我不想将我所有的子视图都定义为 IBOutlets,所以我认为迭代子视图会更合适。

        for (id subview in self.subviews) {
            if ([subview isKindOfClass:[UIView class]]) {
                UIView *theView = (UIView*)subview;
                if (theView.tag == 16) {
                    // tag 16 is specific to some UIViews... do stuff
                }
            }
            else if ([subview isKindOfClass:[UILabel class]]) {
                UILabel *theLabel = (UILabel*)subview;

                if (theLabel.tag == 21) {
                    // tag 17 is specific to some UILabels... do stuff
                }
                else
                {
                    // no tag... do stuff 
                }

            }
        }

我认为这会更健壮,但是由于UILabels 是从 s 继承UIView的,所以我不能使用这种方法。我知道更改 if 订单可以使其正常工作,但依赖 if 子句的订单感觉不太好

我要问的是,在这种情况下最合乎逻辑的方法是什么?我应该使用viewWithTag:函数而不是循环遍历ids 和强制转换吗?

4

2 回答 2

5

您可以使用IBOutletCollection. 您创建一个 Array ofUILabels和一个 Array ofUIViews

 @property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *labels;
 @property (strong, nonatomic) IBOutletCollection(UIView) NSArray *views;

您所要做的就是创建@property上面的内容,然后在 IB 中将您想要分组的所有标签连接到此集合,就像您对 IBOutlet 一样。当您想遍历它们时:

for (UILabel *label in self.labels) {
     NSLog(@"labelTag:%i", label.tag);
     // Do what you want with this label
}

for (UIView *view in self.views) {
     NSLog(@"viewTag:%i", view.tag);
     // Do what you want with this view
}
于 2013-02-08T13:21:35.587 回答
3

如果要测试对象的特定类型,请使用isMemberOfClass而不是isKindOfClass,它测试对象是否属于指定类继承自指定类。

于 2013-02-08T13:22:27.007 回答