UILabel文本对齐不起作用(Swift 4)

问题描述 投票:0回答:3

我试图在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
}()

请在下面找到该问题的屏幕截图。我的要求是将文本放在两行中。

enter image description here

ios swift xcode uilabel anchor
3个回答
0
投票

更新以下代码行将解决您的问题:

tv.textAlignment = .center

这会将标签文本与中心对齐。


0
投票

将视图添加为子视图后,尝试设置对齐。

view.addSubview(self.bioTextView)
bioTextView.textAlignment = .center

0
投票

试试这个:

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
}()
© www.soinside.com 2019 - 2024. All rights reserved.