Search code examples
swiftautolayoutsliderconstraintsnslayoutconstraint

constraint rotated vertical uislider


This is how I would like my ui slider constrained.

enter image description here

However the slider is not vertical. To make it vertical I have to use sliderX.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)) but that messes up the contraints. Is there any way to contrasting the slider to the same spot but switching the orientation of the slider. Below is a procure of what the code currently looks like.

enter image description here


Solution

  • You can consider the frame of the view before it is rotated. Imagine a horizontal slider, where should you put it on the screen, and how long should it be, such that when it is rotated by 90 degrees, it looks the way you want?

    For example, you could add the following constraints:

    • the slider's centre X is equal to the safe area's trailing anchor (minus some padding, perhaps)
    • the slider's centre Y is equal to the safe area's centre Y
    • the slider's width is equal to the safe area's height (because when it is rotated the width becomes the height)
    let slider = UISlider(frame: .zero)
    slider.minimumValue = 0
    slider.maximumValue = 1
    slider.value = 0.5
    
    slider.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(slider)
    slider.transform = .init(rotationAngle: .pi / 2)
    NSLayoutConstraint.activate([
        slider.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -30),
        slider.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor),
        slider.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor)
    ])
    

    enter image description here