省略号在UITextView的末尾
如果我有多行不可滚动的UITextView,其文字长度可以放在可见区域,那么文本就像这样切断:
Congress shall make no law respecting an establishment of religion, or
我怎样才能得到文本显示省略号的文本截断,就像这样
Congress shall make no law respecting an establishment of religion, or …
像标签和button等其他控件都具有这种能力。
为什么不使用UILabel
设置numberOfLines
到适当的东西,并获得免费的function?
UITextView
被devise为在string大于视图可以显示的时候滚动。 确保你已经在代码或者你的xib中正确的设置了anchoring和autoresize属性。
以下是一篇关于如何实现自己的省略号的博客post 。
@interface NSString (TruncateToWidth) - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font; @end
#import "NSString+TruncateToWidth.h" #define ellipsis @"…" @implementation NSString (TruncateToWidth) - (NSString*)stringByTruncatingToWidth:(CGFloat)width withFont:(UIFont *)font { // Create copy that will be the returned result NSMutableString *truncatedString = [[self mutableCopy] autorelease]; // Make sure string is longer than requested width if ([self sizeWithFont:font].width > width) { // Accommodate for ellipsis we'll tack on the end width -= [ellipsis sizeWithFont:font].width; // Get range for last character in string NSRange range = {truncatedString.length - 1, 1}; // Loop, deleting characters until string fits within width while ([truncatedString sizeWithFont:font].width > width) { // Delete character at end [truncatedString deleteCharactersInRange:range]; // Move back another character range.location--; } // Append ellipsis [truncatedString replaceCharactersInRange:range withString:ellipsis]; } return truncatedString; } @end
有人告诉我,在iOS 7或更高版本上使用UITextView实际上很容易:
UITextView *textView = [UITextView new]; textView.textContainer.lineBreakMode = NSLineBreakByTruncatingTail;