Multi-line UIButton label with Tail Truncation in iOSon 17 November 2011

Getting a multi-line text UIButton is easy in iOS. Having the tail truncation (see ellipsis) with the multi-line is tricky.

The UIButton resets the frame of the titleLabel when changing the lineBreakMode mode. When set to UILineBreakModeTailTruncation it assumes a single line of text, even if numberOfLines is set greater than 1 on the label. With UILineBreakModeWordWrap, it will have multiple lines, however no truncation ellipsis. This leaves awkwardly worded buttons.

Multi-line Tail
Truncat...

To get tail truncation with word wrap, set your numberOfLines to greater than 1, lineBreakMode to UILineBreakModeTailTruncation and then override the layoutSubviews method.


- (void)layoutSubviews {
  self.titleLabel.frame = self.bounds;
}

Or with taking contentEdgeInsets into account:


- (void)layoutSubviews {
  self.titleLabel.frame = CGRectMake(self.contentEdgeInsets.left,
  self.contentEdgeInsets.top,
  self.bounds.size.width - (self.contentEdgeInsets.left + self.contentEdgeInsets.right),
  self.bounds.size.height - (self.contentEdgeInsets.top + self.contentEdgeInsets.bottom));
}

Unfortunate that a custom subclass is needed, however it is a very simple implementation.

If you enjoyed this, use this shorter link to share: http://the.ichibod.com/s/tail