2

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?

vivek241
  • 666
  • 1
  • 7
  • 18

1 Answers1

5

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];
Wain
  • 118,658
  • 15
  • 128
  • 151
  • What attribute should I set? – vivek241 Nov 01 '13 at 08:24
  • By setting paragraph style with the `NSLineBreakByTruncatingTail` line break mode you will get only single truncated line of text. If you need to show multiple lines with truncation you should use `drawWithRect:options:attributes:context:` with the proper attributes. Check [this answer](http://stackoverflow.com/a/40950193/2797141) for details. – xZenon Dec 03 '16 at 17:01