UIButton
####Objective - C
LXYHyperlinksButton.h
@interface LXYHyperlinksButton : UIButton
{UIColor *lineColor;
}-(void)setColor:(UIColor*)color;
复制代码
LXYHyperlinksButton.m
#import "LXYHyperlinksButton.h"@implementation LXYHyperlinksButton- (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复制代码
####Swift
LXYHyperlinksButton.swift
import UIKitclass LXYHyperlinksButton: UIButton {var lineColor: UIColor!internal func setColor(color:UIColor) {if lineColor == nil {lineColor = UIColor.whiteColor()}lineColor = color.copy() as! UIColorself.setNeedsDisplay()}override func drawRect(rect: CGRect) {let textRect: CGRect = self.titleLabel!.framelet contextRef: CGContextRef = UIGraphicsGetCurrentContext()!let descender: CGFloat = self.titleLabel!.font.descenderif lineColor.isKindOfClass(UIColor) {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, .Stroke)}}
复制代码
##UILabel
LXYHyperlinksLabel.h
@interface LXYHyperlinksLabel : UILabel
{UIColor *lineColor;
}-(void)setColor:(UIColor*)color;
复制代码
LXYHyperlinksLabel.m
#import "LXYHyperlinksLabel.h"@implementation LXYHyperlinksLabel- (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 {[super drawRect:rect];CGRect textRect = self.frame;CGContextRef contextRef = UIGraphicsGetCurrentContext();CGFloat descender = self.font.descender;if([lineColor isKindOfClass:[UIColor class]]){CGContextSetStrokeColorWithColor(contextRef, lineColor.CGColor);}CGContextMoveToPoint(contextRef, descender+1, textRect.size.height + descender+1);CGContextAddLineToPoint(contextRef, textRect.size.width, textRect.size.height + descender+1);CGContextClosePath(contextRef);CGContextDrawPath(contextRef, kCGPathStroke);
}@end复制代码
####Git地址:
github.com/xuanyi0627/…