vivek241
vivek241

Reputation: 664

How do I trim the text and add Ellipsis (...) while using drawInRect: on iOS 7?

I've create a subview and implementing the drawRect: method for custom drawing. How do I achieve a behavior similar to that of a UILabel which automatically adds the Ellipsis (...) if the text is too long to fit in its frame.

Here is the code

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

If the sampleText is long then it just gets clipped to fit within the specified rect. How do I add the '...' appropriately?

Upvotes: 2

Views: 2098

Answers (1)

Wain
Wain

Reputation: 119031

You need to use one of the methods like drawInRect:withAttributes: and use the attributed string attributes to set the line truncation style.


Try:

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

Upvotes: 5

Related Questions