Before I begin, I have visited How to align text inside textView vertically? and How can you rotate text for UIButton and UILabel in Swift? and many other places, but none of the answers outlined in the above links (or any place I've been to) has address my problem. So here's how it goes:
I am trying to display text in a UILabel vertically after the device changes to landscape from portrait.
I've managed to (forcefully) stack them vertically by changing its frame size and setting numberOfLines = 0.
This sort of produces the result I want, except I get white spaces between each character after rotation, elongating the word greatly.
Please check the image below to get a better idea of what I am experiencing.
Ideally, there would be no unnecessary white spaces after rotation, and it would be nice and compact like it is in Portrait.
Does anyone know how I can achieve this? In my example, I am using UILabel, but an answer using UITextView is also fine as long as it works. Below is my code:
import UIKit
class ViewController: UIViewController {
var _W = CGFloat()
var _H = CGFloat()
var wordLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
_W = UIApplication.shared.statusBarOrientation.isPortrait ? view.frame.width : view.frame.height
_H = UIApplication.shared.statusBarOrientation.isPortrait ? view.frame.height : view.frame.width
wordLabel = UILabel()
wordLabel.text = "Text"
view.addSubview(wordLabel)
formatLabel(label: wordLabel, fontSize: 64, color: UIColor.magenta, tag: 1)
}
func formatLabel(label: UILabel, fontSize: CGFloat, color: UIColor, tag: Int) {
label.font = UIFont.boldSystemFont(ofSize: fontSize)
label.textColor = color
label.tag = tag
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 0
positionView(label, isPortrait: UIApplication.shared.statusBarOrientation.isPortrait)
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
positionView(wordLabel, isPortrait: !UIApplication.shared.statusBarOrientation.isPortrait)
}
func positionView(_ view: UIView, isPortrait: Bool) {
if (view.tag == 1) {
if (isPortrait) {
wordLabel.frame = CGRect(x: 0, y: 0, width: _W, height: 80)
wordLabel.center = CGPoint(x: _W/2, y: (_H - _W)/4)
} else {
wordLabel.frame = CGRect(x: 0, y: 0, width: 50, height: _W)
wordLabel.center = CGPoint(x: (_H - _W)/4, y: _W/2)
}
}
}
}