首页 > 代码库 > IOS手动添加的View 在代码中使用(自动布局)autoLayout
IOS手动添加的View 在代码中使用(自动布局)autoLayout
- (void)viewDidLoad { [super viewDidLoad]; UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];//不需要去刻意指定x,y的坐标,可以用CGRectZero btnTest.backgroundColor = [UIColor redColor]; btnTest.layer.borderColor = [UIColor yellowColor].CGColor; btnTest.layer.borderWidth = 2.0; [self.view addSubview:btnTest]; [btnTest setTranslatesAutoresizingMaskIntoConstraints:NO];//将使用AutoLayout的方式布局 //btnTest顶部相对于self.view的顶部距离为100 NSLayoutConstraint *constraintTop = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:100]; //btnTest左侧相对于self.view的左侧距离为100 NSLayoutConstraint *constraintLeft = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1.0 constant:100]; //btnTest右侧相对于self.view的右侧距离为100 NSLayoutConstraint *constraintRight = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:btnTest attribute:NSLayoutAttributeRight multiplier:1.0 constant:100]; //btnTest底部相对于self.view的底部距离为100 NSLayoutConstraint *constraintBottom = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:btnTest attribute:NSLayoutAttributeBottom multiplier:1.0 constant:100]; //水平居中 NSLayoutConstraint *constraintXCenter = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:00.0f]; //垂直居中 NSLayoutConstraint *constraintYCenter = [NSLayoutConstraint constraintWithItem:btnTest attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:00.0f]; //将约束添加到父视图中 [self.view addConstraint:constraintTop]; [self.view addConstraint:constraintLeft]; [self.view addConstraint:constraintRight]; [self.view addConstraint:constraintBottom]; [self.view addConstraint:constraintXCenter]; [self.view addConstraint:constraintYCenter]; }
IOS手动添加的View 在代码中使用(自动布局)autoLayout
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。