。因此,它将通过使用数组触摸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
答案 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];
}