String 如何获取适合受约束大小(如UILabel)的字符串
我有一个非常长的文本,所以我不想使用UITextView,而是想将文本截断为小的块,这些块可以适合宽度和高度为300、400的标签,并且基于块的数量,我想动态创建UILabel并用这些块填充它们 我已经编写了一个方法,但它似乎没有返回适合的实际字符串。它返回较短的字符串 我错过什么了吗? 还有什么我可以做的吗String 如何获取适合受约束大小(如UILabel)的字符串,string,text,size,uilabel,truncate,String,Text,Size,Uilabel,Truncate,我有一个非常长的文本,所以我不想使用UITextView,而是想将文本截断为小的块,这些块可以适合宽度和高度为300、400的标签,并且基于块的数量,我想动态创建UILabel并用这些块填充它们 我已经编写了一个方法,但它似乎没有返回适合的实际字符串。它返回较短的字符串 我错过什么了吗? 还有什么我可以做的吗 - (NSArray *)truncate:(NSString *)text { NSMutableArray *textChunks = [[NSMutableArray all
- (NSArray *)truncate:(NSString *)text
{
NSMutableArray *textChunks = [[NSMutableArray alloc] init];
NSString *chunk = [[NSString alloc] init];
CTFramesetterRef frameSetter;
UIFont *uiFont = [UIFont systemFontOfSize:17.0f];
CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef)uiFont.fontName, uiFont.pointSize, NULL);
NSDictionary *attr = [NSDictionary dictionaryWithObject:(__bridge id)ctFont forKey:(id)kCTFontAttributeName];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:text attributes:attr];
CFRange fitRange;
while (attrString.length>0) {
frameSetter = CTFramesetterCreateWithAttributedString ((__bridge CFAttributedStringRef) attrString);
CGSize framSize = CTFramesetterSuggestFrameSizeWithConstraints(frameSetter, CFRangeMake(0,0), NULL, CGSizeMake(myLabel.frame.size.width, myLabel.frame.size.height), &fitRange);
NSLog(@"height: %f", framSize.height);
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;
}
是的,您需要添加段落样式以使宽度/高度度量正常工作。看见请注意如何使用CTFontGetLeading()获取字体前导,然后将此属性设置为vai CFAttributedStringSetAttributes()