Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto layout horizontal and vertical format together

How to add horizontal and vertical visual format together in the constraintsWithVisualFormat ? There is just horizontal. I want to add V:|-50-[leftButton] and V:|-50-[rightButton] to it. How to do that? Create another NSLayoutConstraint?

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [leftButton setTitle:@"Left" forState:UIControlStateNormal];
    [leftButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:leftButton];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [rightButton setTitle:@"Right" forState:UIControlStateNormal];
    [rightButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:rightButton];

    NSArray *layoutConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-50-[leftButton(>=80)]-50-[rightButton(>=80)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(leftButton, rightButton)];
    [self.view addConstraints:layoutConstraints];
}
like image 818
yong ho Avatar asked Dec 04 '25 06:12

yong ho


2 Answers

You can create as many separate sets of constraints using visual format as you like. You can't mix horizontal and vertical constraints in the same string, but there is nothing stopping you from creating:

H:|-[view]-|

Followed by

V:|-[view]-| 

Think of each VFL statement as expressing layout in a single row or column of the superview.

like image 192
jrturton Avatar answered Dec 05 '25 23:12

jrturton


Oh, I figured out. I should create another constraint like this:

NSLayoutConstraint *leftButtonLayoutConstraint = [NSLayoutConstraint constraintWithItem:leftButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:10.0];
    [self.view addConstraint:leftButtonLayoutConstraint];

Tell me if this is the best way to do this. But it works any way.

like image 27
yong ho Avatar answered Dec 05 '25 22:12

yong ho