Iphone UIButton图像/背景图像怪异

Iphone UIButton图像/背景图像怪异,iphone,cocoa-touch,image,uikit,uibutton,Iphone,Cocoa Touch,Image,Uikit,Uibutton,我的viewcontroller中有一个自定义UIButton,根据加载viewcontroller时变量的值,该按钮应具有红色或蓝色心形的图像。如果用户单击按钮,它将更改域模型中的红色/蓝色值,并且还应切换按钮图像。如果调用ViewWillDisplay中的以下代码,则按钮颜色将正确加载: if ([self.color isBlue]) self.colorButton.imageview.image = [UIImage imageNamed:@"blueHeart.png"];

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

if ([self.color isBlue])
     self.colorButton.imageview.image = [UIImage imageNamed:@"blueHeart.png"];
else
     self.colorButton.imageview.image = [UIImage imageNamed:@"redHeart.png"];
但是当我按下按钮时,我无法让它改变颜色。按下按钮时,将调用my 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
变量中按原样更新,但按钮的颜色不变。(我已经在调试器中验证了所有代码行都按其应该的方式执行。)我尝试使用
[按钮setImage:forState:][/code>和
[按钮setBackgroundImage:forState:][/code>但它们的行为不符合预期。有没有人能告诉我ViewWillAppead:(或ViewDidLoad:)方法和我的toggleColor:方法的步骤?我在这里遗漏了一些东西。

这对我很有用:

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

谢谢布拉德,我想差不多了。还有一点奇怪:当我点击按钮并切换时,由于某种原因,它会在图像周围创建一个轮廓。例如,当按钮为红色,我单击它时,它会变为蓝色,但在边缘留下红色轮廓。看起来红色图像(与蓝色图像大小相同)已被稍微放大并放置在蓝色图像后面的背景中。如果我关闭视图并重新打开,它看起来很好。奇怪的我会玩这个,但可以随意分享想法。我会检查4件事:#1确保按钮是自定义类型,而不是RoundedRect#2确保您的PNG大小相同,并且不会发生缩放。(图像的像素大小应与按钮边框相等(iPhone4的像素大小应为按钮边框的两倍)。#3您可以临时在按钮上设置背景色(button.backgroundColor=[UIColor purpleColor])确保您的图像确实是边到边的,并且您看到的框确实来自其中一个图像文件,而不是视图层次结构中的其他文件。