0

我有 UIButton 实例称为卡。我有一个名为“Representer”的对象,它有一个属性“image”,它是一个 UIImage。我正在尝试在运行时更改按钮图像的值。我在界面生成器中有按钮,并且还用按钮声明了一个 IBOutlet。我写了这段代码:

UIButton *card1 = [[UIButton alloc] init]; 
[card1 setImage:representer.image forState:UIControlStateNormal]; 

编译此代码时,按钮的图像不会改变。请有人帮助我!

4

2 回答 2

3

您首先需要确保您的按钮已连接到 Interface Builder 中的 IBOutlet,您是否使用 Connections Inspector 做到了这一点?

如果您的 .h 中有按钮:

@property (nonatomic, retain) IBOutlet UIButton *option1Button;

然后,在 .m 文件中,调用

[option1Button setImage:representer.image forState:UIControlStateNormal];

在您的代码中,您只是实例化了另一个 UIButton 并在其上设置了图像。这是很好的代码,但与 xib 中的按钮无关。

这绝对假设 IBOutlet 在 Interface Builder 中正确连接。这是它的外观:

在此处输入图像描述

此外,您需要在按钮的图像与按钮的背景图像中保持一致。他们是两个不同的东西。如果您在 Interface Builder 中指定了“图像”,则在代码中执行相同操作,反之亦然,使用 backgroundImage。

于 2012-05-15T02:05:34.103 回答
0

Set a breakpoint at the line where you are changing the image and make sure cardOne is not nil. (or use an NSLog statement.) Broken outlet links are a very common reason that code doesn't work as expected.

于 2012-05-15T02:31:04.700 回答