iOS OC 为button添加下划线

最近做的一个项目里需要在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

直接复制粘贴即可用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容