简体   繁体   中英

UILabel attributed text can't have multiple lines if you change baseline offset attribute

I want to change brackets's baseline offset in a words, like "[推]blablabla".

NSRange range = [text rangeOfString:@"[推]"];
if (range.location == 0) {
    [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(0, 1)];
    [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(range.length-1, 1)];
}

but the second line of the label disappears and gets truncated. Anyone have an idea?

Please use lineBreakMode and numberOfLines Also to call sizeToFit, like this:

label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
[label sizeToFit]; 

The height will be automatically computed.

Thanks

I've did some quick test, and it seems that if you add a whitespace at the first of your string, it will work as expected

// make sure your text looks like @" [推]your content"
if (range.location == 1) {
    [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(1, 1)];
    [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(range.length, 1)];
}

If you using storyboard see the below image, select the Label, then see the Lines is set 0 and Line Breaks set Word Wrap thats solve.

在此处输入图片说明

or if you use code,

Objective C:

LabelName.lineBreakMode = UILineBreakModeWordWrap;
LabelName.numberOfLines = 0;

Swift:

LabelName.lineBreakMode = .ByWordWrapping
LabelName.numberOfLines = 0 

hope its helpful

Did you try using NSMutableParagraphStyle to set lineBreakMode as attribute?

NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
[paragrahStyle setLineBreakMode:NSLineBreakByTruncatingTail];

[attributedText addAttribute:NSParagraphStyleAttributeName value:paragrahStyle range:NSMakeRange(0, [attributedText length])];

like proposed here: UILabel attributedText with multiple line break modes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM