如何在没有间隙的情况下将旋转的UILabels定位在UIStackView中?

时间:2017-11-08 19:46:34

标签: ios swift uistackview

我正在尝试创建一个包含已旋转的UILabel的UIStackView。 UIStackView根据UILabels的非旋转宽度定位UILabels,这样当我希望UILabels直接相邻时会有很大的间隙。我怎样才能正确地重新定位这些元素?

代码:

    let stackView = UIStackView(frame: canvas.bounds)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    canvas.addSubview(stackView)
    stackView.axis = .horizontal
    stackView.topAnchor.constraint(equalTo: canvas.topAnchor, constant: 0).isActive = true
    stackView.bottomAnchor.constraint(equalTo: canvas.bottomAnchor, constant: 0).isActive = true
    stackView.leftAnchor.constraint(equalTo: canvas.leftAnchor, constant: 0).isActive = true

    let label1 = UILabel()
    label1.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
    label1.text = "THREEEEEEEE"
    stackView.addArrangedSubview(label1)

    let label2 = UILabel()
    label2.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
    label2.text = "FOUR"
    stackView.addArrangedSubview(label2)

我看到了什么: enter image description here

UI检查器视图:enter image description here

我的期望: enter image description here

1 个答案:

答案 0 :(得分:1)

为什么不首先尝试将视图添加到堆栈视图,然后旋转堆栈视图?

  let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black

view.addSubview(label)
self.view = view

let label1 = UILabel()
label1.text = "THREEEEEEEE"

let label2 = UILabel()
label2.text = "FOUR"


let stackView = UIStackView(arrangedSubviews: [label1, label2])
stackView.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
stackView.axis = .vertical
stackView.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 100).isActive = true

我使用了视图而不是画布。