UILabel:将换行符模式应用于文本的一部分

考虑一个很长的string,比如“位于美丽的巴尔的摩市中心”。

我的标签对于这个文本来说太小了,现在显示如下:

位于市中心美丽的巴...

我希望位置子string被中间截断而不截断“位于”子string ,如下所示:

位于美丽的城市

UILabel类参考指出这应该是可能的:

如果要将换行符模式应用于文本的一部分,请使用所需的样式信息创build一个新的属性string,并将其与标签关联。 如果不使用样式文本,则此属性应用于text属性中的整个文本string。

在一个示例项目中,只有一个UILabel,我尝试按照以下代码进行操作:

- (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; } 

我的标签看起来还是一样的,最后截断了。

以下是debugging器中的最终结果:

 (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"; } 

有没有人得到这个工作? 我的实现中缺less什么?

你为什么不使用两个UILabel ? 第一个包含文本“位于”,然后第二个包含任何其他文本,你想要的。 然后,您可以将NSLineBreakByTruncatingMiddle属性应用于第二个标签。 你只需要把它们放在一起,就可以得到相同的UILabel

希望这可以帮助!