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];
相关推荐
文件夹__iOS40 分钟前
深入浅出 iOS 对象模型:isa 指针 与 Swift Metadata
ios·swift
*拯10 小时前
Uniapp Android/IOS 获取手机通讯录
android·ios·uni-app
天天打码12 小时前
Lynx-字节跳动跨平台框架多端兼容Android, iOS, Web 原生渲染
android·前端·javascript·ios
lilili啊啊啊14 小时前
iOS safari和android chrome开启网页调试与检查器的方法
android·ios·safari
名字不要太长 像我这样就好1 天前
【iOS】源码阅读(二)——NSObject的alloc源码
开发语言·macos·ios·objective-c
I烟雨云渊T1 天前
iOS实名认证模块的具体实现过程(swift)
ios·cocoa·swift
小鹿撞出了脑震荡2 天前
汇编学习——iOS开发对arm64汇编的初步了解
汇编·学习·ios
小鹿撞出了脑震荡2 天前
「OC」源码学习—— 消息发送、动态方法解析和消息转发
学习·ios·objective-c
恋猫de小郭2 天前
Flutter 合并 ‘dot-shorthands‘ 语法糖,Dart 开始支持交叉编译
android·flutter·ios
恋猫de小郭2 天前
React Native 前瞻式重大更新 Skia & WebGPU & ThreeJS,未来可期
android·javascript·flutter·react native·react.js·ios