我试图找到一种方法来理解 UILabel 实例将在哪个范围内截断文本。我知道如何使用 -sizeWithFont:constrainedToSize:lineBreakMode:
获取字符串占用的大小。
假设我们有一个大约 5 行的 UILabel 和一个长文本,使用上面的方法我可以知道它是否适合。如果它不合适,我想添加另一个 UILabel 和剩余的文本。我这样做是因为 View 布局与图像混合,当图像完成时,我希望在 View 的整个宽度上有一个文本。
我知道使用核心文本我可以在一个 View 中做到这一点,但我更喜欢使用 UILabel 来轻松实现。
/*图像*/##/*文本*/
/*图像*/##/*文本*/
/*图像*/##/*文本*/
/*图像*/##/*文本*/
/*图像*/##/*文本*/
/*****文本*************/
/******文本*************/< br/>
/******文本**************/
最佳答案
好吧,我找到了一个解决方案,答案是重复的 Get truncated text from UILabel
我从该答案中复制修改后的方法,您需要导入 CoreText 框架并确保标签设置为自动换行:
- (NSArray *)truncate:(NSString *)text forLabel: (UILabel*) label
{
NSMutableArray *textChunks = [[NSMutableArray alloc] init];
NSString *chunk = [[NSString alloc] init];
NSMutableAttributedString *attrString = nil;
UIFont *uiFont = label.font;
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
NSDictionary *attr = [NSDictionary dictionaryWithObject:(__bridge id)ctFont forKey:(id)kCTFontAttributeName];
attrString = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];
CTFramesetterRef frameSetter;
CFRange fitRange;
while (attrString.length>0) {
frameSetter = CTFramesetterCreateWithAttributedString ((__bridge CFAttributedStringRef) attrString);
CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0,0), NULL, CGSizeMake(label.bounds.size.width, label.bounds.size.height), &fitRange);
CFRelease(frameSetter);
chunk = [[attrString attributedSubstringFromRange:NSMakeRange(0, fitRange.length)] string];
[textChunks addObject:chunk];
[attrString setAttributedString: [attrString attributedSubstringFromRange:NSMakeRange(fitRange.length, attrString.string.length-fitRange.length)]];
}
return textChunks;
}
关于iphone - 如何获取 UILabel 将截断文本的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17401777/