好的,所以我被困在这个问题上。我正在获取一个包含 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)]];
}