iOS-固定宽度下长字符串的分行

需求:在固定宽度内,返回一个字符串需要显示的每行字符串
思路:Foundation框架并没有提供快相关API来解决这个问题,但是CoreText有,因为可能基础的应用CoreText应用不多,这里给出个sample,有兴趣的可以研究下:

#import "NSString+Lines.h"
#import <CoreText/CoreText.h>

@implementation NSString (Lines)

- (NSArray *)getSeparatedLinesWithFont:(UIFont *)font width:(CGFloat)width {
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:self];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    
    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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • (一)叫我许阡时 “花妹儿,扎一束一百枝的蔷薇,送到唐宁街天和公寓C座8101”,林姐咬了一口西瓜装作纯良无害的模...
    九北鱼阅读 1,388评论 8 28
  • 和儿子去做眼睛理疗,理疗店的老板看我在看《传习录》,说:你怎么那么想不开,看古文难为自己?不知如何回答。读...
    jing2006阅读 944评论 0 4
  • 今天学习了一个小技巧,就是如何让文字在DIV中底部对齐。例如该DIV的高度是60px那么就可以把DIV的行高设置为...
    JustFantasy阅读 3,083评论 0 0