Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add UISLider with Autolayout programmatically

I'm trying to add a UISlider to my view programmatically including constraints so that its width adapts to the whole screen width. This is what I got so far:

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]];
like image 513
luca Avatar asked Jul 31 '26 15:07

luca


1 Answers

Missing self.slider.translatesAutoresizingMaskIntoConstraints = NO; Your code is working fine for me. See the below image

enter image description here

like image 165
Raj Subbiah Avatar answered Aug 03 '26 08:08

Raj Subbiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!