1

I have a UILabel set up to have a maximum of 2 lines, that word-wraps when there is too much content.

I have a problem where when there is only a single word left over, it doesn't bother to wrap and truncates the text.

how can I get it to wrap all text no matter how long the remainder?

(the first example below is only missing 'aves'

Comparison

Donald Duck
  • 6,488
  • 18
  • 59
  • 79
Halpo
  • 2,555
  • 2
  • 20
  • 48
  • check this. http://stackoverflow.com/questions/21728917/nslinebreakbywordwrapping-not-working-ios7 . might help you – Shruti Mar 13 '15 at 12:21
  • I assume this is in Autolayout. Do you set `label.preferredMaxLayoutWidth` anywhere? If you use Autolayout and preferredMaxLayoutWidth is greater than the actual width you will see exactly what you get. I guess it's just a few points greater than the actual width, so the effect does not show with longer strings. – Matthias Bauch Mar 13 '15 at 12:54
  • 1
    I was able to reproduce the problem in a Playground: http://i.imgur.com/aF3QlUQ.png – Matthias Bauch Mar 13 '15 at 13:01

2 Answers2

1

You are missing some information, so this is basically a very educated guess:

I assume you are using Autolayout for this (probably should have tagged it).

The behavior you see can be caused if you have set preferredMaxLayoutWidth of the label to a higher value than what is actually used.

I played around a bit and can now reproduce the result.

Playground Screenshot

As you can see (click it), I set preferredMaxLayoutWidth to 310 in line 13. But the actual width of the label is 299 points (line 36).

The Autolayout engine will use 310 instead of 299 to calculated how many lines are needed. The first strings fits in a line that is 310 pt. wide, the second string does not. That's why only the text in the first label is truncated.

The solution is to not set preferredMaxLayoutWidth. This might have a performance impact or any other negative consequences though. In this case you have to figure out a way to set it to the correct value.

Here is the complete playground, in case someone wants to play with it:

// Playground - noun: a place where people can play

import UIKit

var view = UIView(frame: CGRect(x: 0, y: 0, width: 315, height: 200))
view.backgroundColor = UIColor.lightGrayColor()

func addLabel(view: UIView) -> UILabel {
    let label1 = UILabel()
    label1.numberOfLines = 0
    label1.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.1)
    label1.setTranslatesAutoresizingMaskIntoConstraints(false)
//    label1.preferredMaxLayoutWidth = 310
    view.addSubview(label1)
    return label1
}

let label1 = addLabel(view)
let label2 = addLabel(view)

let views = ["l1" : label1, "l2" : label2]

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[l1]-8-[l2]", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[l1]-|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[l2]-|", options: nil, metrics: nil, views: views))

label1.text = "How to Wear This Spring's Must-Haves"
label2.text = "The Best New Men's Fragrances For Spring 2015"


view.layoutIfNeeded()

view.frame
label1.frame
label1.preferredMaxLayoutWidth

label2.frame
label2.preferredMaxLayoutWidth
Matthias Bauch
  • 88,097
  • 19
  • 217
  • 244
0

1.Calculate the height of the label using the following code snippet

-(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
    CGSize constraint = CGSizeMake(width , 20000.0f);
    CGSize title_size;
    float totalHeight;

    SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
    if ([text respondsToSelector:selector]) {                
        title_size = [text boundingRectWithSize:constraint
                                        options:NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{ NSFontAttributeName : font }
                                        context:nil].size;

        totalHeight = ceil(title_size.height); 
    } else {                
        title_size = [text sizeWithFont:font
                      constrainedToSize:constraint
                          lineBreakMode:NSLineBreakByWordWrapping];                
        totalHeight = title_size.height ;                
    }

    CGFloat height = MAX(totalHeight, 40.0f);
    return height;            
}

2.Create a label like this

UILabel *YourLabel = [[UILabel alloc] init];

YourLabel.numberOfLines = 0;

YourLabel.lineBreakMode =  NSLineBreakByWordWrapping;

CGRect frame = YourLabel.frame;

float height = [self getHeightForText:YourLabel.text 
                             withFont:YourLabel.font
                            andWidth:YourLabel.frame.size.width];
float gap = 2;

YourLabel.frame = CGRectMake(frame.origin.x, 
                                         frame.origin.y, 
                                         frame.size.width, 
                                         height);

Hope this helps

Attribution

Community
  • 1
  • 1
Durai Amuthan.H
  • 28,889
  • 6
  • 148
  • 223