iOS - UILabel一段文字加不同下划線加不同顏色


  • 在UILabel中的一段文字上添加不同顏色,不同下划線

注意: 如果同時給一段文字加上顏色與下划線是沒有下划線效果的,目前不知為什么. 例如:"hello" 給它同時加上下划線與改變字體顏色則只能改變顏色.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
            
    [str  addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT"size:30.0] range:NSMakeRange(0, 5)];
            
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold"size:30.0] range:NSMakeRange(6, 12)];
            
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique"size:30.0] range:NSMakeRange(19, 6)];
    //加下划線
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, 3)];
    
    UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 320, 50)];
    lbl.userInteractionEnabled = YES;
    [self.view addSubview:lbl];
    lbl.attributedText = str;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickStr)];
    [lbl addGestureRecognizer:tap];
}


  • 效果圖:

UIButton下划線設置: http://www.cnblogs.com/adampei-bobo/p/6116469.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM