how to put UISlider vertical?

2019-01-21 07:27发布

问题:

I want to put UISlider in vertically. I have no idea about this, so please help me for this.

回答1:

You have to do this programaticaly. Assuming your UISlider is bound to a variable called slider, add this code in your viewDidLoad method in ViewController.m:

- (void)viewDidLoad {

    [super viewDidLoad];

    CGAffineTransform trans = CGAffineTransformMakeRotation(M_PI * 0.5);
    slider.transform = trans;
}

Let me know if you need any more help on this..



回答2:

As of Xcode 4.2, you can sort of do the same in Interface Builder.

  • Create a slider
  • Show the "Identity Inspector"
  • Add a "User Defined Runtime Attribute"
  • Set the key path to "layer.transform.rotation.z", the type as "String" ("Number" won't allow floating point values) (possible since Xcode 5) and the value to "-1.570795" (-π/2).

Unfortunately, it will still appear as horizontal in Interface Builder.

But you can position the center and don't need to create a custom class, so it might be useful enough in some cases. The effect is the same as ravinsp's code.



回答3:

Swift 3:

slider.transform = slider.transform.rotated(by: CGFloat(0.5 * Float.pi))

// Use 1.5 to invert the shadow of slider if you want



回答4:

In case you work with 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.



回答5:

Using an IBOutlet and setter observers. If you want the max to be at the bottom, divide pi by positive 2

@IBOutlet weak var slider: UISlider! {
    didSet {
        slider.transform = CGAffineTransform(rotationAngle: .pi / -2)
    }
}