1. 建立一個空iOS應用程式(Empty Application).
2. 添加加控制器類. 修改控制器類的viewDidLoad
- (void)viewDidLoad{ [super viewDidLoad]; //建立標題 UILabel *header = [[UILabel alloc] init]; header.text = @"歡迎來到我的世界!"; header.textAlignment = NSTextAlignmentCenter; [self.view addSubview: header]; self.statusLabel = [[UILabel alloc] init]; self.statusLabel.text = @"準備就緒!"; [self.view addSubview: self.statusLabel]; //添加自動布局約束 UILabel *statusLabel = self.statusLabel; [header setTranslatesAutoresizingMaskIntoConstraints: NO]; [statusLabel setTranslatesAutoresizingMaskIntoConstraints: NO]; NSMutableArray *contraits = [NSMutableArray array]; NSMutableDictionary *metrics = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@5, @"HPadding", @5, @"VPadding", @20, @"TopMargin", nil]; NSDictionary *views = NSDictionaryOfVariableBindings(header, statusLabel); [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[header]-HPadding-|" options:0 metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]]; [contraits arrayByAddingObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-HPadding-[statusLabel]-HPadding-|" options:0 metrics:metrics views:views]]; [contraits addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-TopMargin-[header]-(>=0)-[statusLabel]-VPadding-|" options:0 metrics:metrics views:views]]; [self.view addConstraints: contraits]; }
3. 修改AppDelegate.m檔案
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; //加入控制器 self.window.rootViewController = [[DemoViewController alloc] initWithNibName:nil bundle:nil]; [self.window makeKeyAndVisible]; return YES;}
4. 運行程式, 得到如下效果