Search code examples
iosios7uiscrollviewuitextview

UITextView Word Wrapping Unexpected behavior


I have a UITextView with Content and frame size widths equal to 348, but word wrapping happens whenever text width on a line exceeds 338.61. Does anyone know why this might be happening? How can I access the width that the UITextView uses for word wrapping dynamically?


Solution

  • As of iOS 7, yes. It's a combination of textContainerInset and lineFragmentPadding.

    UITextView *textView = ...;
    CGFloat wrappingWidth = textView.bounds.size.width - (textView.textContainerInset.left + textView.textContainerInset.right + 2 * textView.textContainer.lineFragmentPadding);
    

    Which is a nice value to know about. You can use it in boundingRectWithSize: calls, for example:

    CGRect boundingRect = [text boundingRectWithSize:CGSizeMake(wrappingWidth, CGFLOAT_MAX)
                                             options:NSStringDrawingUsesLineFragmentOrigin // this is important
                                          attributes:@{ NSFontAttributeName: textView.font } // and any other attributes of your text
                                             context:nil];
    

    Also cool is the fact that you can set textContainerInset and lineFragmentPadding, so if you want to increase this or have a UITextView that renders with no insets (so it matches a UILabel, for example), you can.