最近做的一个项目里需要在button里的titleLable里添加下滑线,自己搞了半小时,重写了个button。
贴代码:
UnderlineButton.h
#import<UIKit/UIKit.h>
@interface UnderlineButton : UIButton
{
UIColor *lineColor;
}
-(void)setColor:(UIColor*)color;
@end
UnderlineButton.m
#import "UnderlineButton.h"
@implementation UnderlineButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
-(void)setColor:(UIColor *)color{
lineColor = [color copy];
[self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect {
CGRect textRect = self.titleLabel.frame;
CGContextRef contextRef = UIGraphicsGetCurrentContext();
CGFloat descender = self.titleLabel.font.descender;
if([lineColor isKindOfClass:[UIColor class]]){
CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor);
}
CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender+1);
CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender+1);
CGContextClosePath(contextRef);
CGContextDrawPath(contextRef, kCGPathStroke);
}
@end
直接复制粘贴即可用。