How can I make a vertical slider in swift?

别来无恙 提交于 2019-12-03 09:08:34

问题


I was wondering how I can create a vertical slider in swift.

I have tried using .transform and then adding a rotate but this returned an exception and rotated the whole screen. I just need a vertical slider.

I was wondering if anyone know of a way to rotate a slider in swift?

Thanks


回答1:


Assuming you are talking about UISlider :

You were looking in a right direction but probably applied AffineTransformation to the wrong item... You should use UISlider.transform to change it orientation. Here is working code (I did add UISlider using InterfaceBuilder):

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var verticalSlider: UISlider!{
        didSet{
            verticalSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}



回答2:


Options 1:

In Swift 4:

-M_PI_2 is deprecated so Use Double.pi / 2

verticalSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2))

OR

Options 2: for All Objective C and Swift

Key path = layer.transform.rotation.z 
Type     =  String
Value    = -1.570795

Most Imp Note: before and After keypath No Space




回答3:


Use OOP. If you define this rotation as an Extension on UIView, then not only the UIView but also all subclasses that inherit from UIView can be rotated. This of course includes UISlider, but also UILabel, UIButton and about 200? other subclasses... see here list of subclasses for UIView

 extension UIView
 {
    func makeVertical()
    {
         transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
    }
 }

  // usage example:
  sldBoilerTemperature.makeVertical()  

It's good to be aware of inheritance, saves a lot of work. For many Swift extensions to make, it might be a good idea trying to move it upwards in the class hierarchy, like in this example.



来源:https://stackoverflow.com/questions/29731891/how-can-i-make-a-vertical-slider-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!