好的,所以我坚持这个问题。 我正在获取一个2-15个标题(NSStrings)的数组,它被传递到我的自定义类TriButtonGroup中,变成一行/多行按钮!按钮组(UIButton的子类)将水平排列,如果它们都适合!只要所有标题都适合按钮,这就可以正常工作!但是如果水平空间不足,我需要TriButtonGroup将一些按钮移动到一个新行。请参阅附带的图片以获得更好的细节。
这是我的代码,现在,它没有处理字符串太长的情况..我只是无法理解这个! :(
int numButtons = [titleArray count];
int counter = 0;
TriButtonCell *previousButton = nil;
for(NSString *title in titleArray) {
TriButtonCell *button = [[TriButtonCell alloc] initWithFrame:CGRectMake(0,0,0,0)];
[button setTitle:title forState:UIControlStateNormal];
[button setTag:1250+counter];
[button addTarget:nil action:@selector(pushButton:) forControlEvents:UIControlEventTouchDown];
[button.titleLabel setNumberOfLines:1];
[button setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:button];
//Add the correct sizing!
if(previousButton != nil) {
[self addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:previousButton attribute:NSLayoutAttributeRight multiplier:1.0f constant:0.0f]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:previousButton attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];
} else {
//This is the first button! Set the correct width!
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[button]" options:0 metrics:metricsDictionary views:NSDictionaryOfVariableBindings(button)]];
}
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[button(60)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)]];
previousButton = button;
counter++;
}
//Set the distance to the last button!
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[previousButton]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(previousButton)]];
}
答案 0 :(得分:1)
我唯一能想到的就是询问每个TriButtonCell
的{{1}}并手动设计哪些按钮适合一行,并分别为每一行创建约束。
像这样的东西(写在我的头顶,所以它可能不是100%准确)
intrinsicContentSize