iOS label button等设置不同颜色的标题

来源:互联网 发布:数控铣削编程实例简单 编辑:程序博客网 时间:2024/05/18 18:01

 


label

  [[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)];
    attrLabel.attributedText = str;



button

    _button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _button.frame = CGRectMake(200, 200, 100, 20);
    _button.backgroundColor = [UIColor redColor];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"你是好人"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,2)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(2,2)];
    [_button setAttributedTitle:str forState:(UIControlStateNormal)];//此处注意是这个方法
    
        [self.view addSubview:_button];





 

0 0