以编程方式使用Autolayout添加UISLider

时间:2014-02-16 11:14:50

标签: ios autolayout uislider nslayoutconstraint

我正在尝试以编程方式将UISlider添加到我的视图中,包括约束,以便其宽度适应整个屏幕宽度。 这是我到目前为止所得到的:

enter image description here

//2 Add UISlider
self.slider = [[UISlider alloc] init];
[self.view addSubview:self.slider];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.slider
                                                      attribute:NSLayoutAttributeLeft 
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view 
                                                      attribute:NSLayoutAttributeLeft 
                                                     multiplier:1 
                                                       constant:0]];


[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.slider
                                                      attribute:NSLayoutAttributeRight 
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view 
                                                      attribute:NSLayoutAttributeRight 
                                                     multiplier:1 
                                                       constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.slider
                                                      attribute:NSLayoutAttributeBottom 
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:self.view 
                                                      attribute:NSLayoutAttributeBottom 
                                                     multiplier:1 
                                                       constant:0]];

1 个答案:

答案 0 :(得分:4)

缺少self.slider.translatesAutoresizingMaskIntoConstraints = NO;您的代码对我来说很好。见下图

enter image description here