-1

From past few days i am trying to change the background color of UIButton using rgb values but i am not sure why it isn't changing the color. My initial requirement was to change the color of a button by giving the hexadecimal color value. As i couldn't find a way to do that, i am trying it in the following way

UIColor *ButtonColor = [[UIColor alloc]initWithRed:10 green:107 blue:171 alpha:1]; 
self.LoginButton.backgroundColor = ButtonColor;

Am i doing wrong anywhere in the above code ..?. Any help is much appreciated!!!

arun_K
  • 313
  • 1
  • 4
  • 12

3 Answers3

0

Please try the following code.

self.LoginButton.backgroundColor = [UIColor colorWithRed:10.0/255.0 green:107.0/255.0 blue:171.0/255.0 alpha:1.0]; 

May be this is helpful to you.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
0

First make sure your button type is Custom.

_LoginButton = [UIButton buttonWithType:UIButtonTypeCustom];

And try :

 _LoginButton.backgroundColor = [UIColor colorWithRed:10/255.0 green:107/255.0 blue:171/255.0 alpha:1.0];

EDIT : If you are declaring button in class file.

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 100, 100);
    btn.backgroundColor = [UIColor colorWithRed:85/255.0 green:85/255.0 blue:85/255.0 alpha:1];
    [self.view addSubview:btn];
Hima
  • 1,249
  • 1
  • 14
  • 18
  • Thank you for the response. Sorry but it isn't working. I am still getting a white background button instead of the above mentioned color with rob values – arun_K Feb 25 '16 at 13:10
  • Have you taken button in storyboard or defined in the class file? – Hima Feb 25 '16 at 13:11
  • Yup i have taken the button in storyboard. I have created the property and changed the button type to custom in attribute inspector and use the above code in viewdidload. still it isn't working... – arun_K Feb 25 '16 at 13:29
  • Check your outlet again, may be it has erased. – Hima Feb 25 '16 at 13:40
0

UIColor accepts only values between 0.0 and 1.0. So you need to divide your value by 255.

self.LoginButton.backgroundColor = [UIColor colorWithRed:10/255.0 green:107/255.0 blue:171/255.0 alpha:1.0];

Since colorWithRed:green:blue:alpha is a class method there is no need to alloc UIColor first.

https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIColor_Class/#//apple_ref/occ/clm/UIColor/colorWithRed:green:blue:alpha:

To give the color value in hexadecimal see this question: How can I create a UIColor from a hex string?

Community
  • 1
  • 1
Amset
  • 86
  • 3