开发者

UIButton image/background image weirdness

I have a custom UIButton in my viewcontroller that should have either the image of either a red or blue heart depending on the value of a variable when the viewcontroller is loaded. If the user clicks on the button, it changes the Red/Blue value in the domain model and should also toggle the button image. The button color will load correctly if I call the following code in ViewWillAppear:

if ([self.color isBlue])
     self.colorButton.imageview.image = [UIImage imageNamed:@"blueHeart.png"];
else
     self.colorButton.imageview.image = [UIImage imageNamed:@"redHeart.png"];

But I can't get it to change color when I press the button. When the button is pressed, my toggleColor: action method is called:

- (IBAction)toggleColor:(id)sender
{
    if ([self.color isBlue])
    {
        [self.color makeRed];
        self.colorButton.imageView.image = [UIImage imageNamed:@"redHeart.png"];
    }       

    else 
    {
        [self.color makeBlue];
        self.colorButton.imageView.image = [UIImage imageNamed:@"blueHeart.png"];
    }
}

The values are updated in the color variable as they should be, but the color of the button does not change. (I've verified in the debugger that all the lines of code are executed as they should be.) I've tried using the [button setImage: forState:] and [button setBackgroundImage: forState:] but they do not behave as expected. Could someone please just walk me开发者_如何学JAVA through the steps for both the ViewWillAppear: (or ViewDidLoad:) method and my toggleColor: method? I'm missing something here.


This worked for me:

- (void) viewDidLoad {     
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(50, 40, 30, 30);
    [button setImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"blue.png"] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(toggleButtonImages:) forControlEvents:UIControlEventTouchUpInside];     
    [self.view addSubview:button];
}

-(void) toggleButtonImages:(UIButton *)button {
    UIImage *temp = [button imageForState:UIControlStateNormal];
    [button setImage:[button imageForState:UIControlStateSelected] forState:UIControlStateNormal];
    [button setImage:temp forState:UIControlStateSelected];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜