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];
相关推荐
FairGuard手游加固18 小时前
iOS 游戏加固技术解析:代码混淆、资源加密、内存保护与重签名检测
安全·游戏·macos·unity·ios·objective-c
思盛iOS签名上架19 小时前
iOS企业签名原理是什么?
macos·ios·cocoa
Daniel_Coder20 小时前
我用 SwiftUI + GRDB 做了一个「按时吃药·服药提醒」App
ios·swiftui·swift·widgetkit
Patrick_Wilson1 天前
iOS 第三方浏览器图片下载失败问题
前端·ios·浏览器
悟空瞎说2 天前
NSNotificationCenter(NotificationCenter)官方文档白话翻译 + API 详解 + Swift 实战
ios
末代iOS程序员华仔2 天前
iOS个人开发者账号申请为啥会被卡住
ios·swift·figma
MaoJiu2 天前
从纹理采样到局部形变:实时瘦鼻 Shader 算法解析
ios
奈斯先生Vector2 天前
从“能调用”到“可替换”:Coze 多模型 API 编排层设计指南
linux·运维·人工智能·ubuntu·平面·ios
DogDaoDao2 天前
HarmonyOS 深度解析:从微内核到 ArkTS 工程实战
android·linux·ios·华为·程序员·harmonyos·harmonyos next