将UIImage设置为自定义UIButton的问题

时间:2012-08-06 14:19:05

标签: ios uiimageview uibutton

我的UIViewController有两个属性:UIImageViewUiButton。它们IBOutlets上的Interface Builder已正确连接。我的问题是,当我实例化这个视图并设置两个属性时,只设置了UIImageView。我的UIButtoncustom按钮,我正在尝试为其分配UIImage。这是我的代码:

MyViewController *viewController = [[MyViewController alloc]initWithNibName:@"MyViewController" bundle:nil];

[viewController view];

viewController.myImageView.image = [UIImage imageNamed:@"image1.png"];

viewController.myButton.imageView.image = [UIImage imageNamed:@"image2.png"];

关于我做错什么的任何想法?

3 个答案:

答案 0 :(得分:2)

看起来好像需要使用特定方法来设置UIButton的图像而不是访问属性的setter。那个方法是:

[viewController.myButton setImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal];
//Or some other variant of UIControlState such as UIControlStateSelected, UIControlStateDisabled, UIControlStateHighlighted, etc.

答案 1 :(得分:1)

替换

viewController.myButton.imageView.image = [UIImage imageNamed:@"image2.png"];

[viewController.myButton setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal];

应该有效

答案 2 :(得分:1)

这不是你为按钮设置图像的方式,你应该使用

[viewController.myButton setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal];