NSLineBreakByTruncatingMiddle

NSLineBreakByTruncatingMiddle

本文介绍了如何截断UILabel中字符串中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有黑暗骑士在下午7:45升起我需要将它装入固定宽度的UILabel(适用于iPhone)。我怎么能把截断作为黑暗骑士Ris ......在晚上7:45,而不是黑暗骑士在7:4升起......?

Say I have The Dark Knight Rises at 7:45pm and I need to fit that into a fixed-width UILabel (for iPhone). How would I make that truncate as "The Dark Knight Ris... at 7:45pm" rather than "The Dark Knight Rises at 7:4..."?

推荐答案

UILabel有这个属性:

UILabel has this property:

@property(nonatomic) NSLineBreakMode lineBreakMode;

您可以通过将其设置为NSLineBreakByTruncatingMiddle来启用该行为。

You enable that behaviour by setting it to NSLineBreakByTruncatingMiddle.

编辑

我不明白你只想截断一个字符串的一部分。然后阅读:

I din't understand that you wanted to truncate only a part of the string.Then read this:

示例

因此甚至还有一个用于设置段落样式的类:NSParagraphStyle,它也有可变版本。

所以让我们说你有一个你想要应用该属性的范围:

So there is even a class for setting the paragraph style: NSParagraphStyle and it has also it's mutable version.
So let's say that you have a range where you want to apply that attribute:

NSRange range=NSMakeRange(i,j);

你必须创建一个NSMutableParagraphStyle对象并将它的lineBreakMode设置为NSLineBreakByTruncatingMiddle.Notice,你也可以设置它很多其他参数。所以我们这样做:

You have to create a NSMutableParagraphStyle object and set it's lineBreakMode to NSLineBreakByTruncatingMiddle.Notice that you may set also a lot of other parameters.So let's do that:

NSMutableParagraphStyle* style= [NSMutableParagraphStyle new];
style.lineBreakMode= NSLineBreakByTruncatingMiddle;

然后为该范围内标签的attributedText添加该属性.intribiveText属性是NSAttributedString,而不是NSMutableAttributedString,因此您必须创建一个NSMutableAttributedString并将其分配给该属性:

Then add that attribute for the attributedText of the label in that range.The attributedText property is a NSAttributedString, and not a NSMutableAttributedString, so you'll have to create a NSMutableAttributedString and assign it to that property:

NSMutableAttributedString* str=[[NSMutableAttributedString alloc]initWithString: self.label.text];
[str addAttribute: NSParagraphStyleAttributeName value: style range: range];
self.label.attributedText= str;

请注意,NSAttributedString还有很多其他属性,请检查。

Notice that there are a lot of other properties for a NSAttributedString, check here.

这篇关于如何截断UILabel中字符串中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:43