iphone - 如何截断 UILabel 中字符串中的字符串?

标签 iphone objective-c ios uikit views

假设我有晚上 7:45 的黑暗骑士崛起,我需要将其放入固定宽度的 UILabel(适用于 iPhone)。我如何将其截断为“The Dark Knight Ris... at 7:45pm”而不是“The Dark Knight Rises at 7:4...”?

最佳答案

UILabel 有这个属性:

@property(nonatomic) NSLineBreakMode lineBreakMode;

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

编辑

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

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.

示例

所以甚至还有一个用于设置段落样式的类:NSParagraphStyle,它也有可变版本。
因此,假设您有一个要应用该属性的范围:

NSRange range=NSMakeRange(i,j);

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

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

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

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

注意 NSAttributedString 还有很多其他属性,检查 here .

关于iphone - 如何截断 UILabel 中字符串中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13906431/

相关文章:

iphone - 为什么 UIButton 标题不显示?

ios - 从字典中查找空值的捷径技术?

ios - UISlider 不工作,只显示一半的轨道

ios - 我的 iOS 7 相机覆盖层有什么问题?

ios - 使用 UIAppearence 更改 UIViewController 的直接 subview 的背景颜色

iphone - 学习适用于 iPhone 的 Quartz 和/或 openGL 资源?

iphone - 如何从 url 加载图像到 UITableViewCell?

objective-c - ARC什么时候工作?编译还是运行时?

iphone - iOS Facebook SDK-检索 friend 个人资料图片

objective-c - 在 Cocoa 中创建半透明、带边框的圆角窗口?