androniennn
androniennn

Reputation: 3137

Buttons and auto layout

I want to build such interface: enter image description here

With auto layout disabled, I successfully created those 6 buttons and well adjusted them through code in function of screen's height. However, when disabling auto layout, all other controllers become "messy" so I tried to create/adjust those buttons with auto layout enabled. And there is NO WAY to achieve such interface with auto layout enabled. My question is, is there any trick, solution to adjust those 6 buttons with auto layout enabled? Or perhaps there is a library? I'm really stacked. Thank you for your help.

Upvotes: 0

Views: 1138

Answers (2)

rdelmar
rdelmar

Reputation: 104082

I see you found an answer, but I'll post mine anyway, because it uses a different approach. Trying to get the constraints correct in IB (in iOS 6) when there are so many dependencies among the 6 buttons is difficult (because of the constraints the system adds for you in IB), so I did it in code. I did it in such a way that the buttons take the whole screen in any size screen or any orientation without having to check the screen size:

@interface ViewController ()
@property (strong,nonatomic) NSMutableDictionary *viewsDict;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewsDict = [NSMutableDictionary dictionary];
    for (int i=1; i<7; i++) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [b setTitle:[NSString stringWithFormat:@"Button%d",i] forState:UIControlStateNormal];
        [b setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self.viewsDict setObject:b forKey:[NSString stringWithFormat:@"b%d",i]];
        [self.view addSubview:b];
    }

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[b1][b2(==b1)]|" options:0 metrics:nil views:self.viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[b3][b4(==b3)]|" options:0 metrics:nil views:self.viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[b5][b6(==b5)]|" options:0 metrics:nil views:self.viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[b1][b3(==b1)][b5(==b1)]|" options:0 metrics:nil views:self.viewsDict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[b2][b4(==b2)][b6(==b2)]|" options:0 metrics:nil views:self.viewsDict]];
}

Upvotes: 2

robinkunde
robinkunde

Reputation: 1000

With autolayout, you will definitely want to wrap those six views in another UIView to prevent layout interactions between the buttons and other views. If that UIView has a fixed height and width, it might be as simple as that.

Upvotes: 0

Related Questions