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];
相关推荐
Memory沙漏4 小时前
IOS如何免费申请开发者证书(uniapp开发)
ios·uni-app
StarkCoder11 小时前
打造炫酷浮动式 TabBar:让 iOS 应用导航更有格调!
前端·ios
2501_9400940213 小时前
索尼PSP游戏资源下载 推荐中文汉化ios格式合集分享开源掌机模拟器都支持
游戏·ios·cocoa
2501_9160074717 小时前
iOS性能调试工具终极指南,从系统底层到多端协同的全方位优化实践(2025版)
android·ios·小程序·https·uni-app·iphone·webview
私人珍藏库17 小时前
Miraplay – iOS端类TVbox可添加解析源的影视聚合播放器+解析影视源
ios·应用·tv·影视
2501_9159214317 小时前
iOS崩溃日志深度分析与工具组合实战,从符号化到自动化诊断的完整体系
android·ios·小程序·uni-app·自动化·cocoa·iphone
2501_916008891 天前
没有源码如何加密 IPA 实战流程与多工具组合落地指南
android·ios·小程序·https·uni-app·iphone·webview
CocoaKier1 天前
微信与苹果就小程序支付达成和解,iOS用户有望在小程序内直接使用苹果支付
ios·apple
QuantumLeap丶1 天前
《uni-app跨平台开发完全指南》- 07 - 数据绑定与事件处理
vue.js·ios·uni-app