iOS_NSAttributedString根据宽度返回每行文案

2022-07-20 14:50:13 浏览数 (3)

NSAttributedString根据宽度返回每行文案

代码语言:javascript复制
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSAttributedString (MOLine)

/// 根据width返回每一行的内容
/// @param width 纯文字宽度,需要删除容器内边距
- (nullable NSArray <NSAttributedString *> *)qnb_separatedLinesWithWidth:(CGFloat)width;

@end
代码语言:javascript复制
#import "NSAttributedString MOLine.h"
#import <CoreText/CoreText.h>

@implementation NSAttributedString (MOLine)

/// 根据width返回每一行的内容
/// @param width 纯文字宽度,需要删除容器内边距
- (nullable NSArray <NSAttributedString *> *)qnb_separatedLinesWithWidth:(CGFloat)width {
    if (self.length <= 0) {
        return nil;
    }
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)self);
    CGRect frame = CGRectMake(0, 0, width, CGFLOAT_MAX);
    CGPathRef path = CGPathCreateWithRect(frame, nil);
    CTFrameRef ctFrame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil);
    
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(ctFrame);
    NSMutableArray <NSAttributedString *> *linesArray = [NSMutableArray array];
    
    [lines enumerateObjectsUsingBlock:^(id  _Nonnull line, NSUInteger idx, BOOL * _Nonnull stop) {
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
    
        NSAttributedString *lineString = [self attributedSubstringFromRange:range];
        [linesArray addObject:lineString];
    }];
    
    CFRelease(ctFrame);
    CGPathRelease(path);
    CFRelease(frameSetter);

    return linesArray;
}

@end

0 人点赞