1

I'm trying to create a UIStackView containing UILabels that have been rotated. The UIStackView is positioning the UILabels based on their non-rotated widths, such that there is a large gap when I would expect the UILabels to be directly adjacent. How can I correctly reposition these elements?

Code:

    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)

What I'm Seeing: enter image description here

UI Inspector View: enter image description here

What I Expect: enter image description here

Software2
  • 2,358
  • 1
  • 18
  • 28

1 Answers1

1

Why don't you try to add the views to the stack view first, and then rotate the stack view?

  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

I used the view instead of the canvas.

  • This would rotate any other items added to the stack view. While this would solve the simplified example presented here, the goal is to add rotated text to a far more complicated stack view. – Software2 Nov 08 '17 at 23:49
  • you can always embed stack views in other stack views – user2840482 Nov 09 '17 at 07:36