美文网首页
富文本NSMutableAttributedString

富文本NSMutableAttributedString

作者: 剪刀_石头_布 | 来源:发表于2017-04-26 17:11 被阅读29次

    一、文本中划线

    在iOS10.3后,文本中如果包含中文,那么之前的中划线设置方法会失效,我们只需要增加一个富文本属性:

    NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle)

    就可以啦。代码如下:

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 50)];

    label.text = @"gfrrr加一个中划线_egre";

    label.textAlignment = NSTextAlignmentCenter;

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

    [attributeMarket setAttributes:@{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle], NSBaselineOffsetAttributeName : @(NSUnderlineStyleSingle), NSFontAttributeName:[UIFont systemFontOfSize:25.0], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(0,label.text.length)];

    label.attributedText = attributeMarket;

    [self.view addSubview:label];

    效果图:

    文本中划线

    当然了,如果要添加下划线,只需要改变富文本的一个属性就可以,把上面的中划线改变为下划线,也就是把

    NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]这个富文本属性改为下面这个就可以啦

    NSUnderlineStyleAttributeName: [NSNumbernumberWithInteger:NSUnderlineStyleSingle]

    文本下划线

    二、文本大小颜色改变

    可以是一段个别文字改变大小和改变颜色,代码如下:

    UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, self.view.frame.size.width - 40, 180)];

    newLabel.numberOfLines = 0;

    newLabel.textAlignment = NSTextAlignmentCenter;

    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"让一段字中某几个字发生变化{大小、颜色的变化}"];

    [attr setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:25.0], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(14, 5)];

    newLabel.attributedText = attr;

    [self.view addSubview:newLabel];

    效果图:

    改变个别文字

    相关文章

      网友评论

          本文标题:富文本NSMutableAttributedString

          本文链接:https://www.haomeiwen.com/subject/zfqwzttx.html