給UILabel 或者 UIButton標題加底線

來源:互聯網
上載者:User

標籤:ios   uibutton   uilabel   底線   

方法一:

    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

#import <UIKit/UIKit.h>@interface HyperlinksButton : UIButton{    UIColor *lineColor;}-(void)setColor:(UIColor*)color;@end

HyperlinksButton.m 

#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 同理可得。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.