多行UILabel没有自动换行?
是否有可能有一个由多个\n
-delimited行组成的UILabel
具有其宽度的行>标签宽度被截断而不被包裹?
假设我有一些文字如下:
- 这是一个非常长的文本第一行太长,不适合水平
- 短线
- 另一条短线
我想要这样出现在我的UILabel
:
这是一个非常长的第一行文字。 2.短线 3.另一条短线
然而发生了什么是我得到这个:
这是一段非常长的文本 这是太长,以适应水平 2.短线...
第三行正在切断。 我已经把行数设置为3
,但是它仍然包裹着第一条长线。 我在标签上设置换行属性似乎并不重要 – 它总是包装第一行。 有什么办法可以防止在标签上完全包装?
我不认为这是可能的任何设置,你可以适用于你的标签。 一种方法是将string分解成单独的行,截断任何需要它的行,使其(具有添加的省略号)适合于一行,然后将string换行并换行。 像这样的东西应该适用于任何数量的线路,
@interface ViewController () @property (weak, nonatomic) IBOutlet UILabel *label; @property (nonatomic) CGFloat ellipsisWidth; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *text = @"This is a really long first line of text that is too long to fit horizontally\nShort line\nAnother short line"; NSString *ellipsis = @"..."; self.ellipsisWidth = [ellipsis sizeWithAttributes:@{NSFontAttributeName:self.label.font}].width; __block NSMutableString *truncatedString = [@"" mutableCopy]; [text enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { [truncatedString appendFormat:@"%@\n", [self oneLineOfString:line withFont:self.label.font]]; }]; NSString *finalString = [truncatedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; self.label.numberOfLines = 0; self.label.text = finalString; } -(NSString *)oneLineOfString:(NSString *) aLine withFont:(UIFont *) font { __block NSString *singleLine = nil; __block NSString *lastFragment; [aLine enumerateSubstringsInRange:NSMakeRange(0, aLine.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { NSString *textFragment = [aLine substringToIndex:(substringRange.location + substringRange.length)]; CGRect textRect = [textFragment boundingRectWithSize:CGSizeMake(CGFLOAT_MAX ,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil]; if (textRect.size.width >= self.label.bounds.size.width - self.ellipsisWidth) { singleLine = [lastFragment stringByAppendingString:@"..."]; *stop = YES; } lastFragment = textFragment; }]; if (!singleLine) singleLine = aLine; // it doesn't need to be truncated, so return the passed in line return singleLine; }
如果要按字符而不是按字来截断,则可以将NSStringEnumerationByComposedCharacterSequences而不是NSStringEnumerationByWords传递给enumerateSubstringsInRange的options参数:options:usingBlock :.
当然,你可以轻松地做到这一点。 堆叠3个标签在彼此的顶部,并给每一个你的文字的一行:)
- Objective-C – 与C ++桥接的缺点?
- 在iPad上的UIInterfaceOrientation期间更改UIViews
- 具有圆angular和阴影的UIBarButtonItem
- 在superview.superview(sorting)透明的UILabel textColor
- 将UIButton锚定到UITableViewController视图的底部
- (已解决)在调用numberOfRowsInSection时,TableView初始化程序中设置的variables会被遗忘
- 有内置的通讯录应用程序的自定义URLscheme吗?
- mapView:didTapMarker没有select标记
- 为什么我的UITabBar在纵向加载时向下移动20个像素?