如何在Swift中制作一个垂直滑块?

17

我想知道如何在Swift中创建一个垂直滑动条。

我尝试使用.transform,然后添加旋转,但是这会返回一个异常并旋转整个屏幕。我只需要一个垂直滑块。

我想知道是否有人知道如何在Swift中旋转滑块?

谢谢

4个回答

38

假设您在谈论< strong> UISlider :

您的方向是正确的,但可能将< em> AffineTransformation 应用于错误的项目... 您应该使用< strong> UISlider.transform 来更改其方向。 这是有效的代码(我使用InterfaceBuilder添加了UISlider):

import UIKit

class ViewController: UIViewController {

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

4
如果您正在使用Swift 3,您应该使用CGAffineTransform.init(rotationAngle: CGFloat(-M_PI_2))来进行旋转。 - grabury
6
使用更清晰的语法编写Swift 3代码:CGAffineTransform(rotationAngle: -CGFloat.pi)。该代码表示对一个仿射变换进行旋转,旋转角度为负的π弧度。 - nathangitter
2
实际上 CGAffineTransform(rotationAngle: -CGFloat.pi/2) - Pokotuz
1
更简短的写法:CGAffineTransform(rotationAngle: -.pi/2) - exp

11

选项1:

在Swift 4中:

-M_PI_2已被废弃,因此请使用Double.pi / 2

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

或者(OR)

选项2:适用于所有Objective C和Swift

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

输入图像描述

最重要的注意事项:keypath之前和之后没有空格。


5

使用面向对象编程(OOP)。如果您将此旋转定义为UIView的扩展,则不仅UIView而且所有继承自UIView的子类都可以旋转。当然,这包括UISlider,还包括UILabel,UIButton和大约200个其他子类...请参见此处的UIView子类列表

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

  // usage example:
  sldBoilerTemperature.makeVertical()  

了解继承是很好的,可以节省很多工作。对于许多需要制作Swift扩展的情况,尝试将其向上移动到类层次结构中可能是个好主意,就像这个例子一样。


1

使用约束实现Swift-5垂直滑块

func transformSlider(){
    var constraints = [NSLayoutConstraint]()
    ControlSlider.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/2))
    ControlSlider.translatesAutoresizingMaskIntoConstraints = false
    constraints.append(ControlSlider.widthAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.8))
    constraints.append(ControlSlider.centerYAnchor.constraint(equalTo: self.centerYAnchor))
    let sliderWidth = (ControlSlider.frame.height * 0.8)/2
    print(sliderWidth)
    constraints.append(ControlSlider.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: (20-sliderWidth)))
    NSLayoutConstraint.activate(constraints)
}

1
你的答案需要添加另一个第三方工具。 - siemian
只需在Storyboard中创建一个UISlider,并为其创建一个名为ControlSlider的outlet即可,无需第三方组件。然后调用此函数。 - Thomas Mani
这个不起作用。 - Marcus Kim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接