最近项目需要从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;
}