自动布局:将UI组件放置在屏幕正中
将一个 UI 组件放置到屏幕的中央。换句话说,你想你想将一个视图放置到其父视图的中央位置,使用限制条件。
创建两个限制条件:一个是将目标视图的 center.x 位置排列在其父视图的 center.x 位置,并且另外一个是将目标视图的 center.y 位置排列在其父视图的 center.y 位置。
代码:(有问题,为什么代码用button不显示)
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; /*1.创建按钮*/ UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // 标示是否自动遵循视图布局约束 默认为YES //Auto Layout 要和UIViewAutoresizing 区分下 //为了不和autosizing冲突,我们设置No myButton.translatesAutoresizingMaskIntoConstraints = NO; [myButton setTitle:@"button" forState:UIControlStateNormal]; [myButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [self.view addSubview:myButton]; UIView *superView = myButton.superview; /*2.创建约束条件让按钮的高度控制在视图中心 Create the constraint to put the button horizontally in the center */ NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem:myButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeCenterX multiplier:10.f constant:0.0f]; /*3.Create the constraint to put the button vertically in the center */ NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:myButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]; /*Add the constants to the superview of the button*/ [superView addConstraints:@[centerXConstraint,centerYConstraint]]; } /* Suport rotation of device to all orientation 这个视图控制器视图告诉 iOS:它支持所有设备支持的方向,来证明按钮确实会放置到屏幕的中央而忽视设备的类型和他的方向。*/ -(NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskAll; }