Word wrap not working on my UILabel

7.9k views Asked by At

My app uses a custom cell to display products in a tableview. The product name when used on an iPhone 5 was running off the end so I set it to wrap which doesn't work. Each cell is populated in my Customcell class using the code below, I've added a couple of lines to the brandTxt label which again does not work.

public func configure(#text: String?, placeholder: String) {
    if (placeholder == "1")
    {
        brandItemLabel.text = text
        brandItemLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        brandItemLabel.numberOfLines = 2
    }
    else if (placeholder == "2")
    {
        brandSmallLabel.text = text

    }
    else if (placeholder == "3")
    {
        uomCodeLabel.text = text

    }
    else if (placeholder == "4")
    {
        codeLabel.text = text

    }
    else if (placeholder == "6")
    {
        var image = UIImage(named: "Blank.jpg")
        if let url = NSURL(string: text!) {
            if let data = NSData(contentsOfURL: url) {
                image = UIImage(data: data)
            }
        }
        var imgViewLbl = UIImageView(image: image) as UIImageView
        imgViewLbl.frame = CGRect(x: 10, y: 4, width: 90, height: 90)
        customView.addSubview(imgViewLbl)
    }
}

I've also tried using constraints but that is not working either

I've since added the code below using preferredMaxLayoutWidth as well as setting the Preferred Width to Explicit in Size Manager and added Constraints to set the size and height as well as the position.

public func configure(#text: String?, placeholder: String) {
    if (placeholder == "1")
    {
        brandItemLabel.text = text
        brandItemLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        brandItemLabel.numberOfLines = 2
        brandItemLabel.preferredMaxLayoutWidth = 330
    }

The UILabel is still not wrapping in spite of these changes

2

There are 2 answers

5
i89 On BEST ANSWER

When you are targeting iOS 6 until 8 or higher, you have to explicitly set the preferredWidth attribute on the UILabel. You have to do it, if the label has more than one line. See also preferredMaxLayoutWidth:

So you just need to specify this value (in most cases it's good to go to the storyboard, click on the label, go to the "Size Inspector" and just click on 'explicit' next to "Preferred Width").

0
Purnima Naik On

Checking Follow Readable Width in Size Inspector and setting larger height, did it for me!