UIButton图像/背景图像怪异

时间:2010-07-01 21:58:47

标签: iphone cocoa-touch image uikit uibutton

我的viewcontroller中有一个自定义UIButton,它应该具有红色或蓝色心脏的图像,具体取决于加载viewcontroller时变量的值。如果用户单击该按钮,则会更改域模型中的红/蓝值,还应切换按钮图像。如果我在ViewWillAppear中调用以下代码,则按钮颜色将正确加载:

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

但按下按钮时,我无法改变颜色。按下按钮时,我的toggleColor:action方法被调用:

- (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"];
    }
}

值在color变量中应更新,但按钮的颜色不会改变。 (我已经在调试器中验证了所有代码行都按原样执行。)我尝试使用[button setImage: forState:][button setBackgroundImage: forState:],但它们的行为并不像预期的那样。请问有人请告诉我ViewWillAppear :(或ViewDidLoad :)方法和我的toggleColor:方法的步骤?我在这里错过了一些东西。

1 个答案:

答案 0 :(得分:0)

这对我有用:

- (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];
}