自定义带下划线文本的UIButton

转载自 http://mobile.51cto.com/hot-404798.htm,略有改动

UnderLineButton.h代码
@interface UnderLineButton : UIButton

+ (UnderLineButton *) underLineButton;

@end
UnderLineButton.m代码
@implementation UnderLineButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

+ (UnderLineButton *) underLineButton {
    UnderLineButton * button = [[UnderLineButton alloc] init];
    return [button autorelease];
}

// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGRect textRect = self.titleLabel.frame;
    
    //need to put the line at top of descenders (negative value)
    CGFloat descender = self.titleLabel.font.descender+2.0f;
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    //set to same color as text
    CGContextSetStrokeColorWithColor(contextRef, self.titleLabel.textColor.CGColor);
    
    CGContextMoveToPoint(contextRef, textRect.origin.x, textRect.origin.y + textRect.size.height + descender);
    
    CGContextAddLineToPoint(contextRef, textRect.origin.x + textRect.size.width, textRect.origin.y + textRect.size.height + descender);
    
    CGContextClosePath(contextRef);
    CGContextDrawPath(contextRef, kCGPathStroke);
}

@end
原文地址:https://www.cnblogs.com/benbenzhu/p/3394459.html