ios UILabel加删除线

首先生成一个继承与UILabel的类SFPStrikeThroughAndUnderLineLabel

一,在.h文件里

@interface SFPStrikeThroughAndUnderLineLabel : UILabel

{

    BOOL _isWithStrikeThrough;   

}

 @property (nonatomic, assign) BOOL isWithStrikeThrough; //控制是否显示删除线

@property (nonatomic, assign) CGFloat strikeThroughLineWidth;//设置删除线的宽度

@property (nonatomic, retain) NSArray *strikeThroughRGBAlphaArray;//设置删除线的颜色,数组里面的元素分别是RGB以及alpha值也就是说该数组有四个元素

@end

二,在.m文件里

#import "SFPStrikeThroughAndUnderLineLabel.h"

 

@implementation SFPStrikeThroughAndUnderLineLabel

@synthesize isWithStrikeThrough = _isWithStrikeThrough;

@synthesize strikeThroughRGBAlphaArray = _strikeThroughRGBAlphaArray;

@synthesize strikeThroughLineWidth = _strikeThroughLineWidth;

 

- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

        

        self.strikeThroughRGBAlphaArray = [[NSArrayalloc]initWithObjects:@"0",@"0",@"0",@"1", nil];//默认删除线的颜色是黑色切实不透明的,给个默认值,建立对象时该属性可以不必赋值

        self.strikeThroughLineWidth = 1;//默认删除线的宽度是1pix

        

        

    }

    returnself;

}

 

 

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

    // Drawing code

    

    if (self.isWithStrikeThrough)//显示删除线

    {

        CGContextRef c = UIGraphicsGetCurrentContext();

        

        CGFloat color[4] = {[[self.strikeThroughRGBAlphaArrayobjectAtIndex:0] floatValue], [[self.strikeThroughRGBAlphaArrayobjectAtIndex:1] floatValue], [[self.strikeThroughRGBAlphaArrayobjectAtIndex:2] floatValue], [[self.strikeThroughRGBAlphaArrayobjectAtIndex:3] floatValue]};

        CGContextSetStrokeColor(c, color);

        CGContextSetLineWidth(c, self.strikeThroughLineWidth);

        CGContextBeginPath(c);

        CGFloat halfWayUp = (self.bounds.size.height - self.bounds.origin.y) / 2.0;

        CGContextMoveToPoint(c, self.bounds.origin.x, halfWayUp );

        CGContextAddLineToPoint(c, self.bounds.origin.x + self.bounds.size.width, halfWayUp);

        CGContextStrokePath(c);

    }

    [super drawRect:rect];

}

三,使用:添加SFPStrikeThroughAndUnderLineLabel.h文件

 SFPStrikeThroughAndUnderLineLabel *oneLabel = [[SFPStrikeThroughAndUnderLineLabelalloc]initWithFrame:CGRectMake(20, 20, 100, 200)];

    oneLabel.backgroundColor = [UIColorwhiteColor];

    oneLabel.numberOfLines = 0;

    oneLabel.text = @"朱冬玲,我爱你一万年;朱冬玲,我爱你一万年;朱冬玲,我爱你一万年;朱冬玲,我爱你一万年;朱冬玲,我爱你一万年";

    oneLabel.isWithStrikeThrough = YES;

//    下面这两个属性可设可不设值,他们设的都有默认值

//    oneLabel.rgbAlphaArray = [NSArray arrayWithObjects:@"255",@"255",@"0",@"1", nil];

//    oneLabel.strikeThroughLineWidth = 20;

    [self.view addSubview:oneLabel];

注意:这是给UILabel整个控件加删除线(一个label只会有一条删除线),而不是给label的text加删除线 

posted @ 2014-03-13 05:23  shidaying  阅读(1516)  评论(0编辑  收藏  举报