限定UIlabel寬高計算能裝下多少文字(筆記)

//根據(jù)指定的大小,對字符串進行分頁,計算出每頁顯示的字符串區(qū)間(NSRange)

    - (NSArray *)pageRangeArrayWithConstrainedToSize:       (CGSize)size
    {
    NSAttributedString *attributedString = self;
NSMutableArray * resultRange = [NSMutableArray array];
CGRect rect = CGRectMake(0, 0, size.width, size.height);

//    以下方法耗時 基本再 0.5s 以內(nèi)
// NSDate * date = [NSDate date];
NSInteger rangeIndex = 0;//剩余的字數(shù)
do {
    NSUInteger length = MIN(600, attributedString.length - rangeIndex);
    NSAttributedString * childString = [attributedString attributedSubstringFromRange:NSMakeRange(rangeIndex, length)];
    CTFramesetterRef childFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) childString);
    UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRect:rect];
    CTFrameRef frame = CTFramesetterCreateFrame(childFramesetter, CFRangeMake(0, 0), bezierPath.CGPath, NULL);
    
    CFRange range = CTFrameGetVisibleStringRange(frame);
    NSRange r = {rangeIndex, range.length};
    if (r.length > 0) {
        [resultRange addObject:[NSValue valueWithRange:r]];
    }
    rangeIndex += r.length;
    CFRelease(frame);
    CFRelease(childFramesetter);
} while (rangeIndex < attributedString.length && attributedString.length > 0);
//NSTimeInterval millionSecond = [[NSDate date] timeIntervalSinceDate:date];
//NSLog(@"耗時 %lf", millionSecond);
return resultRange;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容