13

I have a UITextView showing some dynamic content that can vary in size. The textview has no scrolling allowed and its size is independent from the content. Given its auto-layout constraints, the text view has a different horizontal size on iphone5 and iPhone6plus for example.

What I would like is my text to be clipped when necessary with 3 dots at the end like that “…”. (there is a "More" UIButton launching safari below the UITextView)

I’m not sure if there is a UITextView property or if i should consider some code that checks how many characters the textview can display in the current circumstances and modify my string to be shown accordingly (cutting and appending @“…”).

Thank you.

MikaelW
  • 1,145
  • 4
  • 11
  • 29

2 Answers2

40

Try setting the UITextView line break mode. It works just like UILabel and should use "..." at the end.

self.textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;

See https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSTextContainer_Class_TextKit/index.html#//apple_ref/occ/instp/NSTextContainer/lineBreakMode

Rory McKinnel
  • 7,936
  • 2
  • 17
  • 28
  • hello, it doesn't seem to work. I wonder what i'm doing wrong. maybe it's incompatible with another property? I'm doing nothing special. – MikaelW Sep 23 '15 at 11:15
  • 1
    What do you see happen when you set a string that is too large? You may need to set the `maximumNumberOfLines` to a value suitable for the collapsed view to force it to truncate. – Rory McKinnel Sep 23 '15 at 11:20
  • you need to also set scrolling as false: textView.isScrollEnabled = false textView.textContainer.lineBreakMode = .byTruncatingTail – Tinkerbell Jan 18 '17 at 11:37
  • 3
    Also, please note that if the line that is truncated ends with a new line, the "..." won't appear. ie if you have something like "Hello\nHow\nAre you" and you set `maximumNumberOfLines` to 2, then you will see "Hello\nHow" and not "Hello\nHow..." –  Aug 22 '17 at 14:14
  • @LeGom: Is there any official documentation for cases like "Hello\nHow\nAre you"? – Niraj May 16 '18 at 12:30
2

If you don't need to edit the content of the text view from the user and you are only displaying content, then use UILabel.

above white background it the text view and the text with 4 lines is the UILabel, i assume you are trying to implement something like this.

Only change the line break mode to "Truncate Tail" and set the no of lines to value you desire.

enter image description here

enter image description here

Arpit Dhamane
  • 503
  • 7
  • 19