美文网首页
ios 获取UILabel等文字控件的行数

ios 获取UILabel等文字控件的行数

作者: songjk | 来源:发表于2020-07-20 17:29 被阅读0次

根据文字内容、字体大小和宽度限制计算文本控件的行数

-(NSInteger)rowsOfString:(NSString *)text withFont:(UIFont *)font withWidth:(CGFloat)width
{
if (!text || text.length == 0) {
    return 0;
}
CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
[attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
CFRelease(myFont);
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0,0,width,MAXFLOAT));
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
return lines.count;
}

相关文章

网友评论

      本文标题:ios 获取UILabel等文字控件的行数

      本文链接:https://www.haomeiwen.com/subject/svpykktx.html