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

11,365

Solution 1

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

Solution 2

This is how I solved my problem: You have to set the view of the XIB file to default, if you don't change it to default you will not be able to change the background colour from the original colour that was set.

For example if you set the background colour to red, even if you change it programmatically it will stay read and not only that but things like view.layer.cornerRadius will not work as well.

So basically change the background colour of the view in the XIB file to default and set it programmatically.

Solution 3

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];
 }];
Share:
11,365
Ranjit
Author by

Ranjit

Passion to code for iPhone :)

Updated on June 04, 2022

Comments

  • Ranjit
    Ranjit almost 2 years

    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