iOS使用核心文本將字符串切割爲字符串數組

前言

開發中某些狀況下,會遇到一些特殊要求,好比須要將一段文本按照固定寬度分割成字符串數組,這裏提供一段使用核心文本切割字符串的方法。數組

Swift代碼

import UIKit
extension String {
    ///根據字體和寬度切割字符串
    func separatedLines(with font: UIFont, width: CGFloat) -> [String] {
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key(kCTFontAttributeName as String), value: CTFontCreateWithName((font.fontName) as CFString, font.pointSize, nil), range: NSRange(location: 0, length: attributedString.length))
        let frameSetter = CTFramesetterCreateWithAttributedString(attributedString)
        let path = CGMutablePath()
        path.addRect(CGRect(x: 0, y: 0, width: width, height: 100000), transform: .identity)
        let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, nil)
        let lines = CTFrameGetLines(frame)
        var linesArray: [String] = []
        for line in (lines as Array) {
            let lineRef = line as! CTLine
            let lineRange: CFRange = CTLineGetStringRange(lineRef)
            let range = NSRange(location: lineRange.location, length: lineRange.length)
            let lineString = (self as NSString).substring(with: range)
            linesArray.append(lineString)
        }
        return linesArray
    }
}
複製代碼

OC代碼

#import <UIKit/UIKit.h>
#import "NSString+Separated.h"
#import <CoreText/CoreText.h>
@implementation NSString (Separated)
/**
 根據字體和每一行寬度切割字符串
 
 @param font 字體
 @param width 寬度
 @return 切割後字符串數組
 */
- (NSArray *)separatedLinesWithFont:(UIFont *)font width:(CGFloat)width {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    [attributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL) range:NSMakeRange(0, attributedString.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, width, 100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [self substringWithRange:range];
        [linesArray addObject:lineString];
    }
    return (NSArray *)linesArray;
}

@end

複製代碼

切割效果

相關文章
相關標籤/搜索