Search code examples
iosswiftuilabelright-to-left

Multiline UILabel with right-to-left text and auto adjusted font size


Below is the code in Swift I used for a 2 line UILabel with adjustsFontSizeToFitWidth set to true, working properly for left-to-right text. I have used EasyPeasy library for setting layout constraints.

let contactLabel = UILabel()
contactLabel.text = "Tell us how we can contact you".localized()
contactView.addSubview(contactLabel)
contactLabel.easy.layout([Leading(), Trailing(), Top(20), Height(60)])
contactLabel.numberOfLines = 2
contactLabel.lineBreakMode = .byTruncatingHead
contactLabel.adjustsFontSizeToFitWidth = true

When I changed the language to Arabic, the text will be broken to two lines properly but shown in LTR mode instead of RTL. How should manage a multiline label to show Arabic text?

I also checked this behavior on iOS 11 and it is working, maybe there is a trick to it in iOS 12.


Solution

  • enter image description hereDon't set a specific height because of that is not expanding to your amount of text.

    Steps 1 - Set top, leading, trailing and height constraint and change height relation to Greater Than or Equal to

    Step 2 - label.numberOfLines = 0

    Step 3 - label.sizeToFit()

    step 4 - label.lineBreakMode = .byTruncatingTail