ios 设置行距和获取文本行数

设置文本行距

objectivec 复制代码
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:12];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.textColor = [UIColor colorWithHexString:@"B3B3B3"];
    label.text = textDes;
    //设置行距
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
        style.lineSpacing  = 3;
        NSMutableDictionary *attributes  = [NSMutableDictionary dictionary];
        [attributes setObject:style forKey:NSParagraphStyleAttributeName];
    label.attributedText = [[NSAttributedString alloc] initWithString:label.text attributes:attributes];

获取文本行数

objectivec 复制代码
//获取文本行数
- (int)getNumberOfLinesWithText:(NSMutableAttributedString *)text andLabelWidth:(CGFloat)width {
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)text);
    CGMutablePathRef Path = CGPathCreateMutable();
    CGPathAddRect(Path, NULL ,CGRectMake(0 , 0 , width, INT_MAX));
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), Path, NULL);
    // 得到字串在frame中被自动分成了多少个行。
    CFArrayRef rows = CTFrameGetLines(frame);
    // 实际行数
    CFIndex numberOfLines = CFArrayGetCount(rows);
    CFRelease(frame);
    CGPathRelease(Path);
    CFRelease(framesetter);
    return numberOfLines;
}

使用

objectivec 复制代码
   //设置行距
    NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
        style.lineSpacing  = 3;
    NSMutableDictionary *attributes  = [NSMutableDictionary dictionary];
        [attributes setObject:style forKey:NSParagraphStyleAttributeName];
    //获取行数
    int nums = [self getNumberOfLinesWithText:[[NSMutableAttributedString alloc] initWithString:self.permissionDes attributes:attributes] andLabelWidth:SCREENWIDTH- 40];
相关推荐
布莱克60517 小时前
Swift 自动引用计数(ARC)详解:原理、循环引用与最佳实践
开发语言·ios·swift·arc·自动引用计数
软件交付观察室1 天前
用户关掉手机定位权限后,原生App还能显示哪些位置?
android·ios·移动开发
KevinWang_3 天前
iOS 开发计划(一) - 通过 Scriptable app 在 iOS 上运行 JavaScript 脚本
javascript·ios
布莱克6053 天前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标
茶底世界之下4 天前
雨天的窗边:用 Awaking 轻轻提亮一盆蕨
ios·app·产品
景彬5 天前
强制升级 Xcode 后,一个 10 年老项目有哪些改动点
ios
茶底世界之下5 天前
海边书店的阴天:用 Awaking 留住青绿与暖灯
ios·app·产品
布莱克6055 天前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
布莱克6056 天前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
茶底世界之下6 天前
旧电影院的红座椅:用 Awaking 留住放映前的光
ios·app·产品