【发布时间】:2019-11-18 11:36:58
【问题描述】:
在开始之前,我访问过How to align text inside textView vertically? 和 How can you rotate text for UIButton and UILabel in Swift? 和许多其他地方,但上述链接(或我去过的任何地方)中列出的答案都没有解决我的问题。所以事情是这样的:
在设备从纵向变为横向后,我试图在 UILabel 中垂直显示文本。
我已经设法(强制)通过更改帧大小和设置 numberOfLines = 0 垂直堆叠它们。
这种产生我想要的结果,除了旋转后每个字符之间有空格,大大延长了单词。
请查看下面的图片以更好地了解我的体验。
理想情况下,旋转后不会出现不必要的空白,并且会像纵向一样美观紧凑。
有谁知道我如何做到这一点?在我的示例中,我使用的是 UILabel,但使用 UITextView 的答案也可以,只要它有效。以下是我的代码:
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)
}
}
}
}
【问题讨论】:
标签: swift text-alignment