【问题标题】:Not be able to change image of UIButton无法更改 UIButton 的图像
【发布时间】:2012-07-10 07:32:52
【问题描述】:

我想在 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 设置为 button 并在 XIB 中分配。

不知道为什么按钮的图片不能设置。

谢谢..

【问题讨论】:

  • 是图片名还是按钮名?
  • 如果你这样做NSLog(@"%@", temp);会发生什么?

标签: iphone objective-c ios5 uibutton


【解决方案1】:

不会工作:

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

您想更改现有UIButtonbackgroundImage。要么现在将 front 添加到视图中并删除旧的,要么使用现有按钮名称而不是 front

【讨论】:

  • NSLog(@"%@",button); 并发布输出。 // “06_asystole.jpg”是你的包的一部分吗?
  • NSLog 是 - >
  • 所以,不要尝试创建新按钮!您需要使用 [nameOfYourIBOutletButton setBackgroundImage:temp forState:UIControlStateNormal]; 更新现有按钮,此图像是您捆绑包的一部分吗?也许您需要清理并将图像文件添加到目标(单击您的项目->单击您的目标->构建阶段->复制捆绑资源->添加图像)...我敢打赌,图像不在您的应用程序。
  • YES 图像是捆绑包的一部分。我已经尝试过你的代码并清理过,但它不起作用
【解决方案2】:
[btn setImage:[UIImage imageNamed:@"06_asystole.jpg"] forState:UIControlStateNormal];

【讨论】:

    【解决方案3】:

    试试这样:

    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 中的按钮,您应该可以直接从编辑器中编辑按钮。

    【讨论】:

      【解决方案4】:

      请试试这个,

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

      希望这会奏效。

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

      在 xib 中选择您的按钮并在属性检查器上设置图像属性。

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

      【讨论】:

        【解决方案5】:

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

        感谢大家的帮助。 :)

        【讨论】:

          【解决方案6】:

          试试这个

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-04-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-24
            • 1970-01-01
            相关资源
            最近更新 更多