Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Backgroundcolor of the UIView through code intead of XIB in ios

I created a windowbased project,then I added a new viewcontroller with xib for user interface checked,and then by entering into the xib,I made some customization to the view,I added few buttons and also changed the background color,

But now I want to change the background color of the view through code and not through xib,

so I tried this in my

-(void)viewDidLoad
{
    UIColor *myColor = [UIColor colorWithRed:(128.0 / 255.0) green:(90.0 / 255.0) blue:(200.0 / 255.0) alpha: 1];
    self.view.backgroundcolor = mycolor;

}

but nothing change happened,so please help me out friends

Thanks & Regards Ranjit

like image 796
Ranjit Avatar asked Nov 04 '11 07:11

Ranjit


2 Answers

What you have typed is correct. It should work. But might I add some correction - define macros, it makes it easy to specify colors -

#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1]
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

[self.view setBackgroundColor: RGB(135, 182, 44)]; //will give a UIColor objct
like image 195
Srikar Appalaraju Avatar answered Oct 18 '22 10:10

Srikar Appalaraju


I have run into a similar problem, and I think I know the reason. You are setting the backgroundColor in the viewDidLoad. I have found any changes I make to the background colour get erased by the time the code gets to the viewDidAppear:.

If you move your setting to the viewDidAppear:, it should work.

Alternatively, you can make it so that it sets the colour in the main thread.

[[NSOperationQueue mainQueue] addOperationWithBlock:
 ^{
     [UIColor colorWithRed:(128.0 / 255.0) green:(90.0 / 255.0) blue:(200.0 / 255.0) alpha: 1];
 }];
like image 21
Erik Allen Avatar answered Oct 18 '22 10:10

Erik Allen