美文网首页iOS
NSMutableAttributedString添加删除线,或

NSMutableAttributedString添加删除线,或

作者: Minoz_min | 来源:发表于2017-03-14 16:51 被阅读385次

在项目中经常会有这个需求,添加删除线,有些是全部文字添加,有些是部分文字添加,这个时候就需要用到NSMutableAttributedString这个来设置:

- (NSMutableAttributedString *)mutableAttributedString
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"我们都是好孩子"];
    NSRange strRange = {0, [attributedString length]};
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12.0f] range:strRange];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:strRange];
    [attributedString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(3, [attributedString length] - 3)];
    return attributedString;
}

特别注意一下,如果是attributedString全部文字都添加删除线,以上这种写法在任何机型任何系统上都没有问题,但是如果只是部分文字需要添加删除线,一定要在NSStrikethroughStyleAttributeName设置这句代码之前添加以下代码:
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:NSMakeRange(0, [attributedString length])];否则在上面代码在5s机型上无效

相关文章

网友评论

    本文标题:NSMutableAttributedString添加删除线,或

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