lable 之删除线初体验
首先生成一个继承与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 = [[ NSArray alloc ] 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 . strikeThroughRGBAlphaArray objectAtIndex : 0 ]floatValue ], [[ self . strikeThroughRGBAlphaArray objectAtIndex : 1 ] floatValue ], [[ self . strikeThroughRGBAlphaArray objectAtIndex : 2 ] floatValue ], [[ self . strikeThroughRGBAlphaArray objectAtIndex : 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 = [[ SFPStrikeThroughAndUnderLineLabel alloc ] initWithFrame : CGRectMake ( 20 , 20 , 100 , 200 )];
oneLabel. backgroundColor = [ UIColor whiteColor ];
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加删除线
浙公网安备 33010602011771号