Objective - C
@interface LXYHyperlinksButton : UIButton
{
UIColor *lineColor;
}
-(void)setColor:(UIColor*)color;
#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 UIKit
class LXYHyperlinksButton: UIButton {
var lineColor: UIColor!
internal func setColor(color:UIColor) {
if lineColor == nil {
lineColor = UIColor.whiteColor()
}
lineColor = color.copy() as! UIColor
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
let textRect: CGRect = self.titleLabel!.frame
let contextRef: CGContextRef = UIGraphicsGetCurrentContext()!
let descender: CGFloat = self.titleLabel!.font.descender
if 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
@interface LXYHyperlinksLabel : UILabel
{
UIColor *lineColor;
}
-(void)setColor:(UIColor*)color;
#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
Github地址:
https://github.com/xuanyi0627/LXYHyperlinks.git