Search code examples
iosobjective-cnsattributedstring

How do I set the color in Attributed button in iOS?


I want to set a title to be underlined with a custom color in an UIButton, NSForegroundColorAttributeName: [UIColor colorWithRed:38 green:105 blue:255 alpha:1] is not applied in my button.

NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:14],NSForegroundColorAttributeName : [UIColor colorWithRed:38 green:105 blue:255 alpha:1], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

NSMutableAttributedString *mat = [[NSMutableAttributedString alloc] initWithString:linkUrl];
[mat addAttributes:attrDict range:NSMakeRange (0, mat.length)];
[self.weblink setAttributedTitle:mat forState:UIControlStateNormal];

Solution

  • Change this line only

      float w = 255.0;
       NSDictionary *attrDict = @{NSFontAttributeName : [UIFont systemFontOfSize:14],NSForegroundColorAttributeName : [UIColor colorWithRed:38/w green:105/w blue:255/w alpha:1], NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};