我试图在UILabel中对齐文本,但它不起作用。文本打印时标签的第二行包含标签的左侧。如何使两条线在标签的中心对齐?谢谢。
let bioTextView: UILabel = {
let tv = UILabel()
tv.text = "This is sample text for a bio label for a user on this platform."
tv.backgroundColor = .clear
tv.textColor = .white
tv.lineBreakMode = .byWordWrapping
tv.numberOfLines = 0
tv.textAlignment = NSTextAlignment.right
return tv
}()
请在下面找到该问题的屏幕截图。我的要求是将文本放在两行中。
更新以下代码行将解决您的问题:
tv.textAlignment = .center
这会将标签文本与中心对齐。
将视图添加为子视图后,尝试设置对齐。
view.addSubview(self.bioTextView)
bioTextView.textAlignment = .center
试试这个:
let bioTextView: UILabel = {
let tv = UILabel()
tv.backgroundColor = .clear
tv.textColor = .white
tv.lineBreakMode = .byWordWrapping
tv.numberOfLines = 0
let textString = NSMutableAttributedString(
string: "This is sample text for a bio label for a user on this platform.",
attributes: [:])
let textRange = NSRange(location: 0, length: textString.length)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
textString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: textRange)
tv.attributedText = textString
return tv
}()