iOS小技巧程序员iOS学习笔记

iOS10.3 NSStrikethroughStyleAttr

2017-04-14  本文已影响1057人  逍遥晨旭

升级iOS10.3之后,给属性文字添加删除线的NSStrikethroughStyleAttributeName不起作用的解决办法。

方法一:

在原有的属性字典里添加NSBaselineOffsetAttributeName就可以了 。

iOS10.3之前的写法是:

NSAttributedString *attributedString = [[NSAttributedString alloc]
                                        initWithString:goodsprice attributes:@{
                                        NSStrikethroughStyleAttributeName :@(NSUnderlineStyleSingle),
                                        NSStrikethroughColorAttributeName : UIColorFromHexValue(0xBBBBBB)
                                        }];
seckillLabel.attributedText = attributedString;

iOS10.3之后的写法是:

NSAttributedString *attributedString = [[NSAttributedString alloc]
                                       initWithString:goodsprice attributes:@{
                                             NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle),
                                             NSStrikethroughColorAttributeName : UIColorFromHexValue(0xBBBBBB),
                                             NSBaselineOffsetAttributeName:@(0)}];
cell.seckillLabel.attributedText = attributedString;

iOS10.3之后要在原有的属性字典里添加NSBaselineOffsetAttributeName键。

效果图:

效果图

方法二:(label只显示一行的情况下,可以使用)

自己定义一个label集成UILabel。通过- (void)drawRect:(CGRect)rect;方法画上去。

- (void)drawRect:(CGRect)rect {
    
    [super drawRect:rect];
    // 取文字的颜色作为删除线的颜色
    [self.textColor set];
    CGFloat w = rect.size.width;
   //再iOS10.3和iOS10.3之前拿到的rect不一致,会导致删除线的位置有些差距,这里可以添加判断系统版本的语句进行处理。也可以直接将高度写死。
    CGFloat h = rect.size.height * 0.5;
    UIRectFill(CGRectMake(0, h, w, 1));
    
}

效果图:


删除线

两种方法的对比:

方法一:可以像iOS10.3以前那样使用,不管一行还是多行都会加删除线的。但是看上去没有方法二的视觉效果好。
方法二:label只显示一行的情况下,可以使用,多行就不能使用。但它的视觉效果要好点,删除线的位置也可以调整。

因为我们整个项目只有给原价格加上删除,没有多长,加上项目经理像调节删除线的位置。我选的是方法二。

倘若有更好的方法可以分享一下。谢谢!!!

上一篇下一篇

猜你喜欢

热点阅读