給UILabel 或者 UIButton標題加下劃線

轉自:http://blog.csdn.net/chaoyuan899/article/details/38306141

方法一:

[objc]?view plain?copy

NSMutableAttributedString?*str?=?[[NSMutableAttributedString?alloc]?initWithString:@"查看所有中獎記錄"];??

NSRange?strRange?=?{0,[str?length]};??

[str?addAttribute:NSUnderlineStyleAttributeName?value:[NSNumber?numberWithInteger:NSUnderlineStyleSingle]?range:strRange];??

[_awardDisplayBtn?setAttributedTitle:str?forState:UIControlStateNormal];??

方法二:

HyperlinksButton.h

[objc]?view plain?copy

#import???


@interface?HyperlinksButton?:?UIButton??

{??

UIColor?*lineColor;??

}??

-(void)setColor:(UIColor*)color;??

@end??

HyperlinksButton.m?

[objc]?view plain?copy

#import?"HyperlinksButton.h"??


@implementation?HyperlinksButton??


-?(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??

直接將這個類 copy 到工程中,,然后將需要加下劃線的 Button 類名改為?HyperlinksButton就可以了,提供了 setColor: 這個接口,可以設置下劃線顏色,代碼很簡單,不解釋了。UILabel 同理可得。

示例結果:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1.NSTimer //暫停if ([timer isValid]) {[timer setFireDate:[N...
    俊月閱讀 1,363評論 0 0
  • 1、設置UILabel行間距 NSMutableAttributedString* attrString = [[...
    FF_911閱讀 1,402評論 0 3
  • 1、禁止手機睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa閱讀 1,139評論 1 6
  • 1.不可變數組轉變為可變數組聲明實例變量的數組 必須記得實現 對于遍歷數組找到對象后 如果還需要查找 記得先結束 ...
    小新xin閱讀 731評論 0 1
  • PPT是設計的藝術,每頁PPT主要有三個元素組成:排版、文字、色彩。在做PPT時應對每頁內容進行設計,立志給聽眾以...
    聞知閱讀 267評論 0 0