NSLayoutConstraint (对UI加约束)
效果
-如何达到让控件永远保持在中间的位置(例如下图)
实现方法
-这里要使用到NSLayoutConstraint对UI进行约束
1 新建一个UISegmentedControl
1 UISegmentedControl *segmentedControll = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Demo 1",@"Demo 2", @"Demo 3",nil]]; 2 segmentedControll.frame = CGRectMake(20, 20, 160, 150);
// 1 3 segmentedControll.translatesAutoresizingMaskIntoConstraints = NO; 4 [self.view addSubview:segmentedControll];
// 1 这一句很重要 否则加约束会出错
2 加约束(控件永远在横向中心)
2 NSLayoutConstraint *constraintLeft = [NSLayoutConstraint 3 constraintWithItem:segmentedControll // 1 4 attribute:NSLayoutAttributeCenterX // 2 5 relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self.view //3 6 attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.f]; //4
// 1 约束对象1 -> item1
// 2 对象1的属性 (此处为对象1的X轴中心)-> attr1
// 3 对象1和2之间的关系 & 对象2 ->item2
// 4 对象2的属性 -> attr2 & 相乘系数 & 加的量
• attr1 >= attr2 * multiplier + costant