0

In my UI there is a UILabel and the text is set to it in the run time. If the text is too long it should show in two lines.

The code of the UILabel is as follows.

    lazy var disLabel:UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .left
        label.font = Fonts.fontForType(fontType: .AktivGroteskRegular, fontSize: 15.0)
        label.lineBreakMode = .byWordWrapping
        label.numberOfLines = 0
        label.backgroundColor = UIColor.red
        label.text = "Hello world. How are you.  XaXaXa
        return label
    }()

Then I set the constraints as follows.

        label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20).isActive = true
        label.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
        label.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true

The output is as follows.

enter image description here

Here there is enough space for the word "you". But it has gone to the second line. Always there is lots of space remains in the first line no matter what the text is.

How to fix this.

udi
  • 3,672
  • 2
  • 12
  • 33
  • 2
    This is a default iOS behavior to avoid widowed lines(single for on a line) and make sure each line has at least 2 words. It already has an answer here - UILabel wrong word wrap in iOS 11 – Dhanesh KM Jun 04 '21 at 13:00
  • Thanks @DhaneshKM for sharing this. Adding the missing link [UILabel wrong word wrap in iOS 11](https://stackoverflow.com/questions/46200027/uilabel-wrong-word-wrap-in-ios-11) – Tarun Tyagi Jun 04 '21 at 13:08

0 Answers0