无法更改UIButton的图像

时间:2012-07-10 07:32:53

标签: iphone objective-c ios5 uibutton

我想在viewWillAppear上设置按钮的图像。

我已尝试遵循所有代码 -

UIButton *front;
    UIImage *temp= [UIImage imageNamed:@"06_asystole.jpg"];
        [front setBackgroundImage:temp forState:UIControlStateNormal];

        //front.imageView.image = [UIImage imageNamed:@"06_asystole.jpg"];
       /// [front setBackgroundImage:[UIImage imageNamed:@"06_asystole.jpg" forState:UIControlStateNormal]];
       // [front setImage:[UIImage imageNamed:@"06_asystole.jpg" forState:UIControlStateNormal]];

我还将IBOutlet设置为按钮并在XIB中分配。

我不知道为什么按钮的图像无法设置。

谢谢..

6 个答案:

答案 0 :(得分:3)

不会工作:

UIButton *front = [[UIButton alloc]init];
UIImage *temp= [UIImage imageNamed:@"06_asystole.jpg"];
[front setBackgroundImage:temp forState:UIControlStateNormal];

您想要更改现有backgroundImage的{​​{1}}。您可以立即将UIButton添加到视图中并删除旧版本,也可以使用现有按钮名称而不是front

答案 1 :(得分:2)

[btn setImage:[UIImage imageNamed:@"06_asystole.jpg"] forState:UIControlStateNormal];

答案 2 :(得分:0)

试试这样:

UIButton *btn = [UIButton buttonWithType: UIButtonTypeCustom]; 
btn.frame = CGRectMake(40, 140, 240, 30); //this should be something valid for you...
UIImage *temp= [UIImage imageNamed:@"06_asystole.jpg"];
        [btn setBackgroundImage:temp forState:UIControlStateNormal];

框架应该是图像的大小或对您有用的东西。

如果您正确链接了xib中的按钮,您应该可以直接从编辑器中编辑按钮。

答案 3 :(得分:0)

请试试这个,

UIButton *front = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *img = [UIImage imageNamed:@"06_asystole.jpg"];
[front setImage:img forState:UIControlStateNormal];

希望这会奏效。

如果您已经为xib添加了一个按钮,则无需创建新按钮。 您可以通过代码或通过xib(如下所示)将图像设置为该按钮

Button image via xib 在xib中选择您的按钮,并在属性检查器上设置image属性。

检查此链接以获取UIButton类参考。link

答案 4 :(得分:0)

我已经通过在我的应用中重新添加图片解决了我的问题。虽然我已经添加了图像到捆绑,但它没有得到该图像的参考。所以我删除了旧图像并重新添加。比它工作正常。

感谢大家的帮助。 :)

答案 5 :(得分:0)

试试这个

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateHighlighted];