I am working in an app which has only portrait support. I need to show a label in landscape orientation so I rotated the text in the label. But the position of the label gets changed. How to rotate the text without changing the position of label? The position of the label should not change. It should be the same as in the first screenshot. The output should be like the last image.
override func viewDidLoad() {
super.viewDidLoad()
rotateLabel(radians: CGFloat.pi/2)
}
func rotateLabel(radians: CGFloat){
rotateLabel.transform = CGAffineTransform(rotationAngle: radians)
}
Before rotation:
After rotation:
Expected output:
You should first create a label with a frame like the one in the second screenshot (width > height), then rotate that to get a frame like in the first screenshot (height > width).
let label = UILabel()
label.text = "The flower is beautiful"
label.backgroundColor = .yellow
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerYAnchor.constraint(equalTo: view.centerYAnchor),
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.heightAnchor.constraint(equalToConstant: 40),
// note the label.width = view.height constraint here
label.widthAnchor.constraint(equalTo: view.heightAnchor)
])
label.transform = CGAffineTransform(rotationAngle: .pi / 2)
If you want to take the safe area into account, you can add a container view. The container view would have a frame similar to the first screenshot, and the label will still have a frame similar to the second screenshot. The container's top and bottom would be constrained to the safe area.
let label = UILabel()
label.text = "The flower is beautiful"
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
label.transform = CGAffineTransform(rotationAngle: .pi / 2)
let container = UIView()
container.backgroundColor = .yellow
container.addSubview(label)
container.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(container)
NSLayoutConstraint.activate([
container.centerXAnchor.constraint(equalTo: view.centerXAnchor),
container.widthAnchor.constraint(equalToConstant: 40),
container.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
container.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
label.centerXAnchor.constraint(equalTo: container.centerXAnchor),
label.centerYAnchor.constraint(equalTo: container.centerYAnchor),
label.widthAnchor.constraint(equalTo: container.heightAnchor),
label.heightAnchor.constraint(equalTo: container.widthAnchor),
])