简体   繁体   中英

iOS: Vertical Alignment of UIButton in iOS

I need to add vertical alignment for the four buttons, so that it should shift few points below. Below is my code, right now its showing four UIButtons at top of horizontal.

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
[button1 setTitle:@"CLOTHING" forState:UIControlStateNormal];
button1.backgroundColor = [UIColor orangeColor];
button1.translatesAutoresizingMaskIntoConstraints = NO;

UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
[button2 setTitle:@"ACCESSORIES" forState:UIControlStateNormal];
button2.backgroundColor = [UIColor orangeColor];
button2.translatesAutoresizingMaskIntoConstraints = NO;

UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];
[button3 setTitle:@"FOOTWEAR" forState:UIControlStateNormal];
button3.backgroundColor = [UIColor orangeColor];
button3.translatesAutoresizingMaskIntoConstraints = NO;

UIButton *button4 = [UIButton buttonWithType:UIButtonTypeSystem];
[button4 setTitle:@"GARMENT" forState:UIControlStateNormal];
button4.backgroundColor = [UIColor orangeColor];
button4.translatesAutoresizingMaskIntoConstraints = NO;

[self.view addSubview:button1];
[self.view addSubview:button2];
[self.view addSubview:button3];
[self.view addSubview:button4];

NSDictionary *views = NSDictionaryOfVariableBindings(button1, button2,button3,button4);
NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-5-[button1]-5-[button2]-5-[button3]-5-[button4]-5-|"
                                                                         options:NSLayoutFormatAlignAllCenterY
                                                                         metrics:nil
                                                                           views:views];

// Find the equal width constraint and set priority to high (750)
for (NSLayoutConstraint *constraint in horizontalConstraints) {
    if (constraint.firstAttribute == NSLayoutAttributeWidth) {
        constraint.priority = UILayoutPriorityDefaultHigh;
    }
}

[self.view addConstraints:horizontalConstraints];

在此处输入图片说明

You are giving a horizontal constraint Change your constraint with this

  NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-15-[button1]-5-[button2]-5-[button3]-5-[button4]"
                                                                         options:0
                                                                         metrics:nil
                                                                           views:views];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM