在iOS 7上使用drawInRect时,如何修剪文本并添加省略号(...)?

时间:2013-11-01 08:12:02

标签: ios nsstring drawrect

我创建了一个子视图并实现了自定义绘图的drawRect:方法。如何实现类似于UILabel的行为,如果文本太长而无法放入其框架中,则会自动添加省略号(...)。

这是代码

- (void)drawRect:(CGRect)rect
{
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:16.0f], NSForegroundColorAttributeName : [UIColor blackColor]};
    [self.sampleText drawInRect:CGRectMake(10.0f, 10.0f, self.frame.size.width - 20.0f, self.frame.size.height - 20.0f) withAttributes:attributes];
}

如果sampleText很长,那么它会被剪裁以适合指定的rect。 如何正确添加'...'?

1 个答案:

答案 0 :(得分:5)

您需要使用drawInRect:withAttributes:之类的方法之一,并使用属性字符串属性来设置线截断样式。


尝试:

NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];
[ps setLineBreakMode:NSLineBreakByTruncatingTail];
[attributes setObject:ps forKey:NSParagraphStyleAttributeName];
相关问题