23

I am customizing an UISlider for my app. I want the slider to be in vertical orientation, but the default UISlider is in horizontal orientation. I couldn't find how to change a UISlider's orientation.

How can I make a vertical slider in XCode?

Daniel S.
  • 6,458
  • 4
  • 35
  • 78
SeongHo
  • 1,040
  • 2
  • 15
  • 39

4 Answers4

49

By default, a UISlider is horizontal (--). If you wish to make it vertical (|) then you must do this programmatically, probably with a CGAffineTransform. For example, you can add this snippet to viewDidLoad or wherever you deem appropriate:

CGAffineTransform trans = CGAffineTransformMakeRotation(M_PI_2);
slider.transform = trans;
Daniel S.
  • 6,458
  • 4
  • 35
  • 78
PengOne
  • 48,188
  • 17
  • 130
  • 149
2

In case you are using auto layouts:

In your viewDidLoad, try:

UIView *superView = self.sizeSlider.superview;
[self.sizeSlider removeFromSuperview];
[self.sizeSlider removeConstraints:self.view.constraints];
self.sizeSlider.translatesAutoresizingMaskIntoConstraints = YES;
self.sizeSlider.transform = CGAffineTransformMakeRotation(M_PI_2);
[superView addSubview:self.sizeSlider];

It does not work with constraints, so the trick is to remove the constraints for your uislider. You might have to resize it manually by setting its frame property.

Antzi
  • 12,831
  • 7
  • 48
  • 74
2

I had a problem with :

CGAffineTransform trans = CGAffineTransformMakeRotation(M_PI_2);
slider.transform = trans;

because I had the code in ViewDidLoad method. Instead, I put the code in ViewDidAppear and it worked fine.

Edit: it doesn't have to be in the ViewDidAppear, ViewDidLoad works fine too (even better). You could disable auto-resize, or set a constraint for the slider you're rotating so the size doesn't change after rotation.

KLD
  • 21
  • 2
0

For Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    // Turn Slider Vertical 
    myslider.transform = CGAffineTransform(rotationAngle: (CGFloat.pi / 2))
LawlessLLC
  • 35
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 23 '22 at 15:28