//// WildCatViewController.h// AutoLayoutDemo//// Created by wildcat on 14-4-20.// Copyright (c) 2014年 com.wildcat. All rights reserved.//#import <UIKit/UIKit.h>@interface WildCatViewController : UIViewController@property(nonatomic,strong) UIButton*button;@end
//// WildCatViewController.m// AutoLayoutDemo//// Created by wildcat on 14-4-20.// Copyright (c) 2014年 com.wildcat. All rights reserved.//#import "WildCatViewController.h"@interface WildCatViewController ()@end@implementation WildCatViewController@synthesize button=_button;- (void)viewDidLoad{[super viewDidLoad];_button=[UIButton buttonWithType:UIButtonTypeRoundedRect];_button.translatesAutoresizingMaskIntoConstraints=NO;[_button setTitle:@"WildCat" forState:UIControlStateNormal];[self.view addSubview:_button];UIView *superView=_button.superview;//加入约束,使按钮在屏幕水平方向的中央NSLayoutConstraint *centerXContraint=[NSLayoutConstraintconstraintWithItem:_buttonattribute:NSLayoutAttributeCenterXrelatedBy:NSLayoutRelationEqualtoItem:superViewattribute:NSLayoutAttributeCenterXmultiplier:1.0fconstant:0.0];//加入约束。使按钮在屏幕垂直方向的中央NSLayoutConstraint *centerYContraint=[NSLayoutConstraintconstraintWithItem:_buttonattribute:NSLayoutAttributeCenterYrelatedBy:NSLayoutRelationEqualtoItem:superViewattribute:NSLayoutAttributeCenterYmultiplier:1.0fconstant:0.0];//给button的父节点加入约束[superView addConstraints:@[centerXContraint,centerYContraint]];}-(NSUInteger)supportedInterfaceOrientations{return UIInterfaceOrientationMaskAll; //屏幕能够旋转}- (void)didReceiveMemoryWarning{[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}@end
不要忘记更改设备能够旋转方向。
执行结果例如以下图:
本文转自:http://1.wildcat.sinaapp.com/?p=42
限制条件和他们要加入到的视图的关系图例如以下:
转载请注明:版权全部点击打开链接
接下来学什么:IOS布局笔记二( Visual Format Language 定义水平和垂直约束)