手寫代碼佈局

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self test1];
    
}
-(void)test1{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"按鈕" forState:UIControlStateNormal];
    button.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.8];
    button.layer.borderColor = [UIColor brownColor].CGColor;
    button.layer.borderWidth = 2;
    [self.view addSubview:button];
    //禁止自動轉換AutoresizingMask
    button.translatesAutoresizingMaskIntoConstraints = NO;
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button1 setTitle:@"按鈕1" forState:UIControlStateNormal];
    button1.backgroundColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:0.8];
    button1.layer.borderColor = [UIColor brownColor].CGColor;
    button1.layer.borderWidth = 2;
    [self.view addSubview:button1];
    button1.translatesAutoresizingMaskIntoConstraints = NO;

    //建立佈局約束
    NSArray *constraints1 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[button]-100-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button)];
    NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[button]-30-[button1(button)]-100-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button,button1)];
    NSArray *constraints3 = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-100-[button1]-100-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(button1)];
    
    [self.view addConstraints:constraints1];
    [self.view addConstraints:constraints2];
    [self.view addConstraints:constraints3];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
相關文章
相關標籤/搜索