Demo Day是我之前网站的一个系列,由于服务器到期一事,导致原有网站数据都丢失了。Demo Day主要通过讲解和学习一些第三方库而生,现在将之前整理的内容重新发出来,后续也会陆陆续续增加新的内容。
StrikeThroughLabel可以为文字添加删除线。效果如下:

从github上下载工程后,运行,StrikeThroughLabelAppDelegate文件中实现简单,主要是下面的代码,代码简单,自己慢慢看。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. CGRect frame = CGRectMake(5, 20, 310, 25); _label = [[StrikeThroughLabel alloc] initWithFrame:frame]; _label.text = @"Strike-through Text"; _label.textAlignment = UITextAlignmentCenter; frame = CGRectMake(5, 50, 310, 25); UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = frame; [button setTitle:@"Toggle Strike-through" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside]; [window addSubview:_label]; [window addSubview:button]; [window makeKeyAndVisible]; return YES; }
这个demo中最关键的是StrikeThroughLabel,StrikeThroughLabel继承UILabel,并重写- (void)drawTextInRect:(CGRect)rect方法,通过strikeThroughEnabled属性控制是否显示删除线。如果需要显示则设置为YES,不显示则设置为NO。
通过重写了strikeThroughEnabled的set方法:
- (void)setStrikeThroughEnabled:(BOOL)strikeThroughEnabled { _strikeThroughEnabled = strikeThroughEnabled; NSString *tempText = [self.text copy]; self.text = @""; self.text = tempText; [tempText release]; }
在drawTextInRect方法中通过计算text的size:
CGSize textSize = [[self text] sizeWithFont:[self font]];
GFloat strikeWidth = textSize.width;
然后再根据textAlignment来计算删除线的Rect
if ([self textAlignment] == UITextAlignmentRight) { lineRect = CGRectMake(rect.size.width - strikeWidth, rect.size.height/2, strikeWidth, 1); } else if ([self textAlignment] == UITextAlignmentCenter) { lineRect = CGRectMake(rect.size.width/2 - strikeWidth/2, rect.size.height/2, strikeWidth, 1); } else { lineRect = CGRectMake(0, rect.size.height/2, strikeWidth, 1); }
然后如果要显示删除线的话,就进行画线,高度为1的线条。
if (_strikeThroughEnabled) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextFillRect(context, lineRect);
}
如果希望更改删除线的颜色可通过设置填充颜色
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
可学到的知识:
1、CGContextRef绘制,填充区域,设置颜色。