自动布局:将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;
}

 

转载于:https://www.cnblogs.com/safiri/p/4036978.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值