我使用下面的函数在下一行添加与Fred和No相同的按钮,但在同一个地方没有相同的按钮大小和文本。
- (IBAction)addAnotherBranchField:(id)sender
{
NSLog(@"Add Another Branch");
UIView *superview = self;
_buttons = [NSMutableArray array];
self.translatesAutoresizingMaskIntoConstraints = NO;
self.backgroundColor = [UIColor clearColor];
_verticalButtonConstraints = [NSMutableArray array];
NSString* previousAnswer = [_datasource valueForField:_field.guid branchIndex:0];
id buttonForLoadedAnswer = nil;
for (FormListOption* option in _field.options) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.translatesAutoresizingMaskIntoConstraints = NO;
//Add a little padding around the text - Using edge insets does not play well with the autolayout so do it with a space instead
[button setTitle:[NSString stringWithFormat:@" %@ ",option.text] forState:UIControlStateNormal];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[_buttons addObject:button];
[superview addSubview: button];
if ([option.text isEqualToString:previousAnswer]) {
buttonForLoadedAnswer = button;
}
}
paddingCounter = paddingCounter + 100;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(200, paddingCounter, 32, 32)];
[addButton setImage:[UIImage imageNamed:@"nav_newanswers.png"] forState:UIControlStateNormal];
[addButton addTarget:self action:@selector(addAnotherBranchField:) forControlEvents:UIControlEventTouchUpInside];
[superview addSubview:addButton];
[superview bringSubviewToFront:addButton];
//Add the constraints
NSMutableDictionary* views = [NSMutableDictionary dictionary];
NSMutableString* visualLayout = [NSMutableString stringWithString:@"H:|-(5)-"];
for (NSInteger i=0; i < [_buttons count]; i++) {
NSString* name = [NSString stringWithFormat:@"button_%d", i];
[views setValue:[_buttons objectAtIndex:i] forKey:name];
[visualLayout appendFormat:@"[%@(>=80)]-", name];
}
[visualLayout appendString:@"(>=10)-|"];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:visualLayout
options:NSLayoutFormatAlignAllBottom
metrics:nil
views:views]];
}
- (void)updateVerticalConstrainsAgain:(UIView*)expandedView padding:(float)padding
{
[self removeConstraints:_verticalButtonConstraints];
[_verticalButtonConstraints removeAllObjects];
NSString* visualFormat = [NSString stringWithFormat: @"V:|[button]-(5)-%@|", expandedView ? [NSString stringWithFormat:@"[expanded]-(20)-"] : @""];
if (padding != 0 && expandedView == nil)
{
visualFormat = [NSString stringWithFormat:@"V:|[button(button)]-(%f)-|",padding];
}
for (UIView* button in _buttons) {
NSMutableDictionary* views = [NSMutableDictionary dictionaryWithObject:button forKey:@"button"];
if (expandedView) {
[views setObject:button forKey:@"expanded"];
}
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:visualFormat
options:0
metrics:nil
views:views];
[self addConstraints:constraints];
[_verticalButtonConstraints addObjectsFromArray:constraints];
}
}
请解释我,我错了。花一整天时间摆脱困境。