Multiple lines of text in UILabel

2019-01-01 16:57发布

Is there a way to have multiple lines of text in UILabel like in the UITextView or should I use the second one instead?

25条回答
无色无味的生活
2楼-- · 2019-01-01 17:14

Set below either in code or in storyboard itself

Label.lineBreakMode = NSLineBreakByWordWrapping; Label.numberOfLines = 0;

and please don't forget to set left, right, top and bottom constraints for label otherwise it won't work.

查看更多
低头抚发
3楼-- · 2019-01-01 17:17
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 17:19

I agree with Jarred Olson, NSLineBreakByWordWrapping is default. I added property sizeToFit like the guide of Gurumoorthy Arumugam to fix it.

If you want the font inside your label to adjust itself to fit into the boundaries of the label. You can use :

textLabel.adjustsFontSizeToFitWidth = YES;

Thanks all.

查看更多
有味是清欢
5楼-- · 2019-01-01 17:19

This code is returning size height according to text

+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
 {
    CGFloat result = font.pointSize+4;
    if (text) 
{
        CGSize size;

        CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, 999)
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil];
        size = CGSizeMake(frame.size.width, frame.size.height+1);
        result = MAX(size.height, result); //At least one row
    }
    return result;
}
查看更多
梦寄多情
6楼-- · 2019-01-01 17:20

In this function pass string that you want to assign in label and pass font size in place of self.activityFont and pass label width in place of 235, now you get label height according to your string. it will work fine.

-(float)calculateLabelStringHeight:(NSString *)answer
{
    CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
    return textRect.size.height;

}
查看更多
泛滥B
7楼-- · 2019-01-01 17:20

Swift 4:

label.lineBreakMode = .byWordWrapping

label.numberOfLines = 0

label.translatesAutoresizingMaskIntoConstraints = false

label.preferredMaxLayoutWidth = superview.bounds.size.width - 10 
查看更多
登录 后发表回答