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];
相关推荐
1024小神9 分钟前
Swift中跨view视图组件实现全局状态共享的方式汇总
ios·swiftui·swift
2501_916007472 小时前
TCP 抓包分析实战,从三次握手到自定义协议解析的完整方法
网络协议·tcp/ip·ios·小程序·uni-app·php·iphone
_大学牲6 小时前
听说你毕业很多年了?那么来做题吧🦶
flutter·ios·app
明君879977 小时前
Flutter横向树形选择器实现方案
android·ios
无痕melody8 小时前
苹果ios手机ipad安装配置ish终端shell工具
ios·智能手机·ipad
mike10239 小时前
swiftUI状态管理
ios·swiftui
2501_9151063211 小时前
H5 混合应用加密实践,从明文资源到安全 IPA 的多层防护体系
android·安全·ios·小程序·uni-app·iphone·webview
kdniao112 小时前
iOS应用集成物流API接口:架构设计、性能优化与用户体验实践指南
ios·性能优化·ux
2501_9160074712 小时前
在 CICD 中实践 Fastlane + Appuploader 命令行,构建可复制的 iOS 自动化发布流程
android·运维·ios·小程序·uni-app·自动化·iphone
2501_9159214312 小时前
从 HBuilder 到 App Store,uni-app 与 HBuilder 项目的 iOS 上架流程实战解析
android·ios·小程序·https·uni-app·iphone·webview