摘选自:http://stackoverflow.com/questions/2630004/underlining-text-in-uibutton
UIUnderlinedButton.h
@interface UIUnderlinedButton : UIButton {
}
+ (UIUnderlinedButton*) underlinedButton;
@end
UIUnderlinedButton.m
@implementation UIUnderlinedButton
+ (UIUnderlinedButton*) underlinedButton {
UIUnderlinedButton* button = [[UIUnderlinedButton alloc] init]; return [button autorelease]; } - (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; CGContextRef contextRef = UIGraphicsGetCurrentContext(); // set to same colour 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); }
上述代码没有考虑显示文本有阴影的情况,下面的的代码做这个处理:
CGFloat descender = self.titleLabel.font.descender; CGContextRef contextRef = UIGraphicsGetCurrentContext(); CGFloat shadowHeight = self.titleLabel.shadowOffset.height; descender += shadowHeight;