UIButton没有显示我的UI按钮Array的背景图像

时间:2014-03-18 08:34:51

标签: ios objective-c uiviewcontroller uibutton nsarray

The Dice is a button and when you touch it it rolles the dice and show the result on the dice button。因此,它将通过使用数组触摸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

3 个答案:

答案 0 :(得分:1)

像这样使用

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

由于您的_diceArray包含UIImage不是图片名称

答案 1 :(得分:1)

  

嗨,你有两种方法来纠正这个程序,第一个改变你的   数组

_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];

答案 2 :(得分:0)

您正在数组中存储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];
}