如何更改Button上的图像集

时间:2011-06-02 07:52:09

标签: iphone ios ipad

我想更改按钮点击事件上的按钮图像。这是我正在尝试的。

-(IBAction)editObjectImage:(id)sender
{
    if (editButtonState == NO)
    {   
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    }
    else
    {
        [editButton setImage:nil forState:UIControlStateNormal];
        [editButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }
}

但我的按钮图像没有变化。代码有什么问题?

4 个答案:

答案 0 :(得分:10)

我认为你无法改变editButtonState。您的代码可以缩减为。

-(IBAction)editObjectImage:(id)sender
{
    UIButton *theButton = (UIButton*)sender;
    if (editButtonState == NO) {   
        [theButton setImage:[UIImage imageNamed:@"done2.png"] forState:UIControlStateNormal];
    } else {
        [theButton setImage:[UIImage imageNamed:@"edit.png"] forState:UIControlStateNormal];
    }

    editButtonState = !editButtonState;
}

答案 1 :(得分:4)

这是我的工作代码:

NSString *shoppingListButtonImageName = @"notepad-selected";

UIImage *slImage = [UIImage imageNamed:shoppingListButtonImageName];
//put a breakpoint here to check that slImage is not nil.

[self.shoppingListButton setImage:slImage forState:UIControlStateNormal];

答案 2 :(得分:2)

点击按钮,你必须像这样设置图像;

[editButton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];

答案 3 :(得分:0)

检查图像是否正确添加(你的[UIImage imageNamed:@“”])没有返回nil? ,否则它应该正常工作。