iOS lable多行取每行字符串

最近项目需要从lable的中去每行添加换行符,在网上找了一些资料,总结了一下怎么处理这个问题。

+(NSString*)getStrfromMorelineby:(UILabel*)lable withfont:(UIFont*)font withdic:(NSDictionary*)dic withstr:(NSString*)str{

CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);

NSDictionary *attributes = @{(NSString *)kCTParagraphStyleAttributeName:[dic valueForKey:NSParagraphStyleAttributeName],(NSString *)kCTFontAttributeName:(__bridge id)myFont,(NSString*)kCTKernAttributeName:[dic valueForKey:NSKernAttributeName]};

NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str];

    [attStr addAttributes:attributes range:NSMakeRange(0, attStr.length)];

CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);

CGMutablePathRef path = CGPathCreateMutable();

CGPathAddRect(path, NULL, CGRectMake(0,0,lable.frame.size.width,100000));

CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);

NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);

NSMutableArray *linesArray = [[NSMutableArray alloc]init];

NSString * mutablestr = @"";

for (id line in lines)

    {

CTLineRef lineRef = (__bridge CTLineRef )line;

CFRange lineRange = CTLineGetStringRange(lineRef);

NSRange range = NSMakeRange(lineRange.location, lineRange.length);

NSString *lineString = [str substringWithRange:range];

        mutablestr =  [mutablestr stringByAppendingString:lineString];

if (![lineString containsString:@"\n"]) {

            mutablestr=[mutablestr stringByAppendingString:@"\n"];

        }

        [linesArray addObject:lineString];

    }

return mutablestr;

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券