2015-04-30 52 views
1

我有我的模型中的标签列表。我想将它们作为标签添加到tagView UIView中作为子视图。constraintsWithVisualFormat可以与动态生成的视图一起使用吗?

NSMutableArray *list = [NSMutableArray new]; 
    for (long i=0; i<_tagView.subviews.count; i++) { 
     UILabel *tagLabel = _tagView.subviews[i]; 
     [tagLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; 
     [list addObject:tagLabel]; 
    } 

    // Create the views and metrics dictionaries 
    NSDictionary *metrics = @{@"height":@25.0}; 
    NSDictionary *views = NSDictionaryOfVariableBindings(list[0], list[1], list[2]); 

// This is experimental as I assume there are three subviews in that. 

    [_tagView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[list[0]]-[list[1]]-[list[2]]-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views]]; 

这是可行的还是必须采取不同的方向?

我忘了补充错误消息我得到:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format: 
list is not a key in the views dictionary. 
|-[list[0]]-[list[1]]-[list[2]]-| 
     ^' 

UPDATE:

键似乎是罚款。 enter image description here

+0

好主意。我刚刚添加了屏幕截图。似乎没关系,不是吗?但仍然没有工作。 – Houman

+0

对不起,我删除了我的评论,因为我对它进行了测试,并且按照您的要求显示。但是,我认为这个关键是由于额外的括号导致了错误。不要使用NSDictionaryOfVariableBindings,而是将密钥添加到可循环字典中,如label1,label2等。 – rdelmar

回答

1

您应该创建自己的字典,这样就可以添加没有额外括号的名称。像“list [0]”这样的名称似乎令解析器感到困惑。

NSMutableDictionary *views = [NSMutableDictionary new]; 
NSMutableArray *list = [NSMutableArray new]; 
     for (long i=0; i<_tagView.subviews.count; i++) { 
      UILabel *tagLabel = _tagView.subviews[i]; 
      [tagLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; 
      [list addObject:tagLabel]; 
      [views setObject:tagLabel forKey:[NSString stringWithFormat:@"label%ld", i]]; 
     } 

     NSDictionary *metrics = @{@"height":@25.0}; 

     [_tagView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[label1]-[label2]-[label3]-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views]]; 
+0

谢谢,没有更多的例外,我也了解它。现在我需要找出为什么这些标签不会出现在我的屏幕上。我想规则是不正确的。 – Houman

+0

@Houman您可能至少需要对其中一个标签进行垂直约束。从你的问题中看不出tagView是什么。它是否有限制(所以它的大小不是零)?您也正在创建度量字典,但没有对它做任何事情。 – rdelmar

相关问题