首页 > 代码库 > iOS lable上的文字自适应(sizetofit)后,获得每一行的内容。返回一个包含所有行内容的数组。

iOS lable上的文字自适应(sizetofit)后,获得每一行的内容。返回一个包含所有行内容的数组。

//  借鉴网络资源
- (void)viewDidLoad { [super viewDidLoad]; UILabel * lb = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, self.view.bounds.size.width-20, 100)]; lb.text = @"骄傲的复活甲卡萨丁涸鲋得水房间卡灰色的加咖啡和撒娇款到发货萨科技回合肥就爱看水电费黄金卡水电费哈是点击看见啊来回飞机熬枯受淡饭盒刷了咖啡壶埃及开发哈空间的凤凰卡积分导航栏"; [self.view addSubview:lb]; lb.font = [UIFont systemFontOfSize:16.0]; lb.numberOfLines = 0; [lb sizeToFit]; NSLog(@"%@",[self getLinesArrOfStringInLbale:lb.text andLblWidth:lb.bounds.size.width andLblFont:lb.font]); } - (NSArray *)getLinesArrOfStringInLbale:(NSString *)contentText andLblWidth:(CGFloat)lblWidth andLblFont:(UIFont *)lblFont{ NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init]; [paragraphStyle setLineSpacing:6]; NSMutableAttributedString *setString = [[NSMutableAttributedString alloc]initWithString:contentText]; [setString addAttribute:NSParagraphStyleAttributeName value:UIPasteboardTypeAutomatic range:NSMakeRange(0, contentText.length)]; [setString addAttribute:NSFontAttributeName value:lblFont range:NSMakeRange(0, contentText.length)]; CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)setString); CGMutablePathRef path = CGPathCreateMutable(); CGPathAddRect(path, NULL, CGRectMake(0, 0, lblWidth, 999999999)); CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame); NSMutableArray *linesArr = [NSMutableArray new]; for (id line in lines) { CTLineRef lineRef = (__bridge CTLineRef)line; CFRange lineRange = CTLineGetStringRange(lineRef); NSRange range = NSMakeRange(lineRange.location, lineRange.length); NSString *lineStirng = [contentText substringWithRange:range]; [linesArr addObject:lineStirng]; } return (NSArray *)linesArr; }

 

iOS lable上的文字自适应(sizetofit)后,获得每一行的内容。返回一个包含所有行内容的数组。