开发者

Change View background in iPhone app based on property

I need to change the background of one of my Views based on a property that will be set when the View is initialized. Is this possible? I've got the background set as a UIImageView and if I set it to an Image in Interface Builder it works, but I can't change the background programatically.

Here is the code I'm using (I based it off a tutorial that loaded an image into a UITableCell):

+ (void) initialize {
/* The threat level images are cached as part of the class,
 so they need to be explicitly retained.
 */
redLevel = [[UIImage imageNamed:@"red.png"] retain];
yellowLevel = [[UIImage imageNamed:@"yellow.png"] retain];
green开发者_开发百科Level = [[UIImage imageNamed:@"green.png"] retain];
}

-(id) initWithThreatLevel:(NSInteger) threatLevel {
if (self = [super initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]]) {
    switch (threatLevel) {
        case 1:
            self.threat_levelImageView.image = greenLevel;
            break;
        case 2:
            self.threat_levelImageView.image = yellowLevel;
            break;
        case 3:
            self.threat_levelImageView.image = redLevel;
            break;
        default:
            self.threat_levelImageView.image = greenLevel;
            break;
    }
}

return self;
}


You should move these assignments to your awakeFromNib method. At initXXX time, NIB connections are usually not yet set up. In awakeFromNib, you're guaranteed that all your connections have been set up.


Make sure threat_levelImageView is an IBOutlet that is connected in Interface Builder. And yes, don't use +initialize for loading the images.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜