iOS开发中富文本的使用及场景举例

在项目开发过程中合理的使用富文本可以减少大量的多余控件,使页面布局更加清爽和易于管理,对多机型适配也有帮助

场景举例:


富文本使用场景

上图示例的红框标注的内容可以使用4个UILabel进行呈现。大大的降低了页面需要管理的view数量。

在基础的修改指定文本颜色、字体、字重之外,还可以在富文本的指定位置添加图片(如文字最后添加的箭头)、修改指定文字的垂直偏移量(可用在一段文本中不同字号的字体Y轴居中显示,如果不进行设置会自动bottom对齐),下方列举代码中都有展示,可自由组合使用,一探究竟。

富文本可设置的属性:

    // 创建一个UILabel

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 200, 100)];

    label.text = @"This is a sample text";

    // 富文本属性设置

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:label.text];

    // 字体设置

    [attributedTextaddAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, [label.text length])];

    // 文字颜色设置

    [attributedTextaddAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];

    // 背景颜色设置

    [attributedTextaddAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(5, 4)];

    // 下划线样式设置

    [attributedTextaddAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(10, 6)];

    // 下划线颜色设置

    [attributedTextaddAttribute:NSUnderlineColorAttributeName value:[UIColor blueColor] range:NSMakeRange(10, 6)];

    // 斜体设置

    [attributedTextaddAttribute:NSObliquenessAttributeName value:@(0.3) range:NSMakeRange(17, 4)];

    // 删除线样式设置

    [attributedTextaddAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(22, 6)];

    // 删除线颜色设置

    [attributedTextaddAttribute:NSStrikethroughColorAttributeName value:[UIColor greenColor] range:NSMakeRange(22, 6)];

    // 行间距设置

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing=10;

    [attributedTextaddAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])];

    // 字体上下偏移  5:向上偏移5像素  如需向下偏移,填负数

    [attributedTextaddAttribute:NSBaselineOffsetAttributeName value:@(5) range:NSMakeRange(28, 4)];


    // 添加图片

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];

    attachment.image= [UIImageimageNamed:@""];

    // 根据需要调整图片位置和大小

    attachment.bounds=CGRectMake(0,0,12,12);

    // 创建一个带有图片的NSAttributedString

    NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment];

    // 将图片插入到富文本中的指定位置

    [attributedTextinsertAttributedString:imageStringatIndex:label.text.length];


    // 设置富文本

    label.attributedText= attributedText;

    // 添加到视图中

    [self.viewaddSubview:label];

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容