views:

36

answers:

2

I am using a UIView object that simply sets the background color to blue. This works fine the first time the code runs, but running the changeBackgroundColor mehod again (from a button action) doesnt change the color to red, even though debugging the code clearly shows the method runs as expected.

Please could someone explain why the view color doesnt update?

Header:

@interface colorClass : NSObject {  
    UIView *myView; 
}

@implementation
...
-(UIView *)changeBackgroundColor {

    myView  = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 500, 245)];

    static int counter = 1;
    if (counter++ %2){
        [mediaView setBackgroundColor:[UIColor blueColor]];
    }else {
        [mediaView setBackgroundColor:[UIColor redColor]];

    }
    return myView;
}
A: 

Have yout tried [yourView setNeedsDisplay] after changing colors ?

Edit:

-(UIView *)changeBackgroundColorof:(UIView *)view {

static int counter = 1;
if (counter++ %2){
    [view setBackgroundColor:[UIColor blueColor]];
}else {
    [view setBackgroundColor:[UIColor redColor]];

}
    return view;
}

you'd have to initialize your view elswhere then with

yourView  = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 500, 245)];

and call

yourview = [self changeBackgroundColorof:yourview];
Gauloises
Hi, thanks for your help, but that doesn't seem to have any effect
As Vladimir points out, you create a new view each time you call this method. Thus you are not modifinig your existing view but just initializing a new one. The new view would have red background color but i think you are not adding this view to the superview, are you ? I edited my post to give you an hint to the soulution
Gauloises
A: 

Thanks to both for pointing me in the right direction. In the end, I needed to create a new init method, and now the code works exactly as I hoped.

-(id)init {

myView      = [[UIView alloc] initWithFrame:CGRectMake(100, 0, 500, 245)];  
return self;

}