-2

I am new in iOS. I want to know how can I change the color for each part of UIButton title.

For example, a part of title in my UIButton is black and another the part of title in my UIButton is yellow

This is the describe image Here is the button that I want

Any help would be appreciated

Linh
  • 57,942
  • 23
  • 262
  • 279
  • no, I can not found any tutorial for this but I can do it in Android – Linh Dec 29 '15 at 02:52
  • 2
    Possible duplicate of [Programmatically change title of UIButton whose title was set in IB as attributed](http://stackoverflow.com/questions/12652198/programmatically-change-title-of-uibutton-whose-title-was-set-in-ib-as-attribute) – Jason Nam Dec 29 '15 at 03:02
  • @JasonNam please see my edit post – Linh Dec 29 '15 at 03:06

2 Answers2

2

U can use NSMutableAttributedString then add it to button with [button setAttributedTitle:attString forState:UIControlStateNormal];

To change color of a range in the Attribute String, read this, basically its just 1 of the attribute dictionary

Read this SO Question

Community
  • 1
  • 1
Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • can you explains more, in the link you give me it . it does not talk about change color. – Linh Dec 29 '15 at 02:59
0

I solve my question by using the code below.
For UILabel

NSMutableAttributedString *text =
[[NSMutableAttributedString alloc]
 initWithAttributedString: self.lblFriendBand.attributedText];

[text addAttribute:NSForegroundColorAttributeName
             value:[UIColor redColor]
             range:NSMakeRange(1, 2)];
[self.lblFriendBand setAttributedText: text];

For UIButton

    NSMutableAttributedString *text2 =
    [[NSMutableAttributedString alloc]
         initWithAttributedString: self.btnFriendName.titleLabel.attributedText];
    [text2 addAttribute:NSForegroundColorAttributeName
                 value:[UIColor redColor]
                 range:NSMakeRange(1, 2)];
    [self.btnFriendName setAttributedTitle:text2 forState:UIControlStateNormal];
Linh
  • 57,942
  • 23
  • 262
  • 279