美文网首页
iOS OC 为button添加下划线

iOS OC 为button添加下划线

作者: Wougle | 来源:发表于2017-02-25 12:57 被阅读0次

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

    直接复制粘贴即可用。

    相关文章

      网友评论

          本文标题:iOS OC 为button添加下划线

          本文链接:https://www.haomeiwen.com/subject/ejogwttx.html