【问题标题】:UIButton not showing my UIbuttons background images for ArrayUIButton 没有显示我的 UIbuttons 背景图像 Array
【发布时间】:2014-03-18 08:34:51
【问题描述】:

。因此,它会通过使用数组和 random() 从图像数组中选择要在图像背景上显示的 IBAction 触摸 UIButton,在按钮上显示随机 1-6 图像的图像

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (IBAction)diceButton:(UIButton *)sender {

    _diceArray=[NSMutableArray arrayWithObjects:
                           [UIImage imageNamed:@"Dice_1.png"],
                           [UIImage imageNamed:@"Dice_2.png"],
                           [UIImage imageNamed:@"Dice_3.png"],
                           [UIImage imageNamed:@"Dice_4.png"],
                           [UIImage imageNamed:@"Dice_5.png"],
                           [UIImage imageNamed:@"Dice_6.png"],nil];

    int index = random() % 5 ;

    for (int i = 0; i < [_diceArray count]; i++) {
        [_diceButton setBackgroundImage:[UIImage imageNamed:[_diceArray objectAtIndex:index]] forState:UIControlStateNormal];

    }
}
@end

【问题讨论】:

  • 你想做什么?
  • 您已经将图像存储在数组中,而不是数组中的名称。所以我喜欢这个 [_diceButton setBackgroundImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];

标签: ios objective-c uiviewcontroller uibutton nsarray


【解决方案1】:

这样使用

[_diceButton setBackgroundImage:_diceArray[index] forState:UIControlStateNormal];  

由于您的 _diceArray 包含 UIImage 的非图像名称

【讨论】:

    【解决方案2】:

    您好,您有两种方法可以更正此程序,第一种方法是更改​​您的 数组

    _diceArray=[NSMutableArray arrayWithObjects:
                               @"Dice_1.png",
                               @"Dice_2.png",
                               @"Dice_3.png",
                               @"Dice_4.png",
                               @"Dice_5.png",
                               @"Dice_6.png",nil];
    

    改变

    [_diceButton setBackgroundImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
    

    【讨论】:

      【解决方案3】:

      您将 UIImage 对象存储在数组中,因此您无法调用

      [UIImage imageNamed:[_diceArray objectAtIndex:index]
      

      所以你需要使用:

      [_diceButton setBackgroundImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
      

      我的建议:使用setImage: 而不是setBackgroundImage:

      for (int i = 0; i < [_diceArray count]; i++)
      {
         [_diceButton setImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
      
         [_diceButton setImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-03
        • 2011-08-23
        • 1970-01-01
        • 2020-10-24
        • 2010-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多