banachbegone
banachbegone

Reputation: 66

UILabel text alignment not working (Swift 4)

I'm trying to align the text in a UILabel but it's not working. The text prints with the second line of the label hugging the left side of the label. How do I make both lines aligned in the center of the label? Thanks.

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
}()

Please find the below screenshot for the issue. My requirement is to fit the text in tow lines.

enter image description here

Upvotes: 1

Views: 8112

Answers (4)

Savely Sakun
Savely Sakun

Reputation: 190

If someone is using UIStackView and has encountered this problem: stackView.alignment can ruin label.textAlignment property. Simply remove stackView.alignment.

Upvotes: 0

Mark Joel Singma
Mark Joel Singma

Reputation: 1

Try this one:

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
}()

Upvotes: 0

mikehobi
mikehobi

Reputation: 116

Try setting the alignment after you have added the view as a subview.

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

Upvotes: 5

Sagar Chauhan
Sagar Chauhan

Reputation: 5823

Update following line fo code will fix your issue:

tv.textAlignment = .center

This will align your label text to center.

Upvotes: -1

Related Questions