简体   繁体   中英

UILabel: applying line break mode to only a portion of the text

Consider a long string, such as "Located in beautiful downtown Baltimore City".

My label is too small for this text, and currently displays it like this:

坐落在美丽的市区Ba…

I would like the location substring to be center truncated without truncating the "Located in" substring , like this:

Located in beautiful…ltimore City

The UILabel class reference indicates this should be possible:

If you want to apply the line break mode to only a portion of the text, create a new attributed string with the desired style information and associate it with the label. If you are not using styled text, this property applies to the entire text string in the text property.

In a sample project, with just one UILabel, I attempt to follow these instructions with the following code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *firstPart = @"Located in";
    NSString *secondPart = @"beautiful downtown Baltimore City";
    NSString *joined = [NSString stringWithFormat:@"%@ %@", firstPart, secondPart];

    NSMutableAttributedString *joinedAttributed = [[NSMutableAttributedString alloc] initWithString:joined];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineBreakMode = NSLineBreakByTruncatingMiddle;

    NSRange detailRange = [joined rangeOfString:secondPart];

    [joinedAttributed addAttribute:NSParagraphStyleAttributeName value:style range:detailRange];

    self.label.attributedText = joinedAttributed;
}

My label still appears the same, with the truncation at the end.

Here's what the final result looks like in the debugger:

(lldb) po joinedAttributed
Located in {
}beautiful downtown Baltimore City{
    NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 5, Tabs (\n    28L,\n    56L,\n    84L,\n    112L,\n    140L,\n    168L,\n    196L,\n    224L,\n    252L,\n    280L,\n    308L,\n    336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0";
}

Has anyone gotten this to work? What's missing from my implementation?

Why don't you use two UILabel s? The first containing the text "Located in " and then the second one containing whatever other text you want. Then you can apply the NSLineBreakByTruncatingMiddle property to the second label only. You just have to position them next to each other to give the illusion that it's the same UILabel .

Hope this helps!

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