我的模型中有一个标签列表。我想将它们作为标签添加到tagView
UIView中作为子视图。
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]]-|
^'
更新:
键看起来很好。
答案 0 :(得分:1)
您应该创建自己的字典,因此可以添加名称,而这些名称不具有您现在获得的额外括号。名称如&#34; list [0]&#34;似乎让解析器感到困惑。
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]];