[英]How to align text inside textView vertically? (Swift)
我发现这在链接到 viewController 的 UITextViews 上完美运行,但我无法弄清楚如何让它为在单独的类中创建的 UITextView 正常工作。
https://stackoverflow.com/a/41387780/8635708
我希望视图高度为三个单位(字符高度),并且内容垂直居中。
另一方面,如果我将视图设置为 4 个单位高,它看起来不错 - 但我没有足够的空间。
这是我所做的(这似乎适用于单行)。
class TestClass: UIView {
var titleView1 = UITextView()
var titleView2 = UITextView()
override func layoutSubviews() {
titleView1.centerVertically()
titleView2.centerVertically()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let h = 3 * GlobalConstants.fontSize // 3 * 14 = 42
var title = "Single Line"
var bounds = CGRect(x: 10, y: 10, width: 100, height: h)
displayTitle(str: title, column: &titleView1, bounds: bounds)
title = "First Line\nSecondLine"
bounds = CGRect(x: 120, y: 10, width: 100, height: h)
displayTitle(str: title, column: &titleView2, bounds: bounds)
}
func displayTitle(str: String, column: inout UITextView, bounds: CGRect) {
let view = UITextView(frame: bounds)
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.blue,
.font: UIFont.italicSystemFont(ofSize: 16)
]
let attributedText = NSMutableAttributedString(string: str, attributes: attributes)
view.attributedText = attributedText
view.textAlignment = .center
view.centerVertically()
self.autoresizesSubviews = true
self.addSubview(view)
}
}
我不相信可以简单地使用NSAttributedString
完成垂直对齐,但如果可能,请告诉我如何!
谢谢!
我将行数设置为 0 并使用 "\\n" 向上或向下移动文本。
非常容易使用!
"Single Line" + "\\n\\n\\n" 将文本向上移动 3 行 "\\n\\n\\n" + "Single Line" 将文本向下移动 3 行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.