zoukankan      html  css  js  c++  java
  • iOS中求出label中文字的行数和每一行的内容

    今天遇到一个需求,需要计算label中文字的行数。想了好久也没想到好的解决方法,就在网上找了下。结果发现一篇文章是讲这个的。这部分代码不但能够求出一个label中文字行数,更厉害的是能够求出每一行的内容是什么; 代码如下。

    #import <CoreText/CoreText.h>

    - (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label{
        NSString *text = [label text];
        UIFont *font = [label font];
        CGRect rect = [label frame];
    
        CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
        [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
        CFRelease(myFont);
        CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
        CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
        NSArray *lines = ( 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 = [text substringWithRange:range];
            CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
            CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
            //NSLog(@"''''''''''''''''''%@",lineString);
            [linesArray addObject:lineString];
        }
    
        CGPathRelease(path);
        CFRelease( frame );
        CFRelease(frameSetter);
        return (NSArray *)linesArray;
    }

     

    文章参照 链接
    函数返回的数组的count 即为label中文字行数 ;数组中元素即为某行内容。

    转载请注明出处:
    原文地址:http://mingxianwei.github.io/2016/05/27/iOS中求出label中文字的行数和每一行的内容
    作者:小土豆

  • 相关阅读:
    HDU ACM 1392 Surround the Trees-&gt;凸包
    JMeter使用记录1 -- JDBC測试
    Html学习笔记4
    c++使用mysql的api连接相关问题
    [Angularjs]ng-select和ng-options
    mysql之字符串操作
    mysql之日期函数
    [sharepoint]Rest api相关知识(转)
    [工具类]泛型集合转换为DataTable
    C#修改文件或文件夹的权限,为指定用户、用户组添加完全控制权限
  • 原文地址:https://www.cnblogs.com/tangyuanby2/p/7091203.html
Copyright © 2011-2022 走看看