这一章的demo主要涉及的是UIPickerView控件
- (void)viewDidLoad {
[super viewDidLoad];
//创建图像变量对象,获取图像类型数据
UIImage *seven = [UIImage imageNamed:@"seven.png"];
UIImage *bar = [UIImage imageNamed:@"bar.png"];
UIImage *crown = [UIImage imageNamed:@"crown.png"];
UIImage *cherry = [UIImage imageNamed:@"cherry.png"];
UIImage *lemon = [UIImage imageNamed:@"lemon.png"];
UIImage *apple = [UIImage imageNamed:@"apple.png"];
for(int i =1; i<=5; i++)
{
//创建图像视图变量对象,获取图像视图类型数据
UIImageView *sevenView = [[UIImageView alloc] initWithImage:seven];
UIImageView *barView = [[UIImageView alloc] initWithImage:bar];
UIImageView *crownView = [[UIImageView alloc] initWithImage:crown];
UIImageView *cherryView = [[UIImageView alloc] initWithImage:cherry];
UIImageView *lemonView = [[UIImageView alloc] initWithImage:lemon];
UIImageView *appleView = [[UIImageView alloc] initWithImage:apple];
NSArray *imageViewArray = [[NSArray alloc] initWithObjects:
sevenView,barView, crownView,cherryView,lemonView,appleView,nil];
//定义选择器中每一列的数据字符类型字符串
NSString *fieldName = [[NSString alloc] initWithFormat:@"column%d",i];
//在选取器中调用imageViewArray数组的值定义到关键字为fieldName字符变量
[self setValue:imageViewArray forKey:fieldName];
[fieldName release];
[imageViewArray release];
[sevenView release];
[barView release];
[crownView release];
[cherryView release];
[lemonView release];
[appleView release];
}
//srandom为随机数生成的起源,设定时间值为空
srandom(time(NULL));
}
//按钮方法,构建老虎机游戏转动
-(IBAction)spin{
//创建判定变量win,定义判定变量为否
BOOL win = NO;
//定义选取器同一行的数值为1
int numInRow = 1;
//定义选取器的最后一行数值为-1
int lastVal = -1;
for(int i = 0; i<5 ;i++)
{
int newValue = random() % [self.column1 count];
//当newValue的值等于最后一行的数值时
if(newValue == lastVal)
//选取器的行数加1,添加下一行数值
numInRow++;
else
numInRow =1;
lastVal = newValue;
//定义选取器中所选行的数值是newValue,所在部分为循环语句的数值i
[picker selectRow:newValue inComponent:i animated:YES];
//读取数值为i的部分
[picker reloadComponent:i];
if(numInRow >= 3)
win = YES;
}
if(win)
winLabel.text = @"WIN!!!";
else
winLabel.text = @"~LOSE~";
}
//定义列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 5;
}
//行数
-(NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [self.column1 count];
}
//显示选取器的行与列
-(UIView *)pickerView:(UIPickerView *)pickerView
viewForRow:(NSInteger)row
forComponent:(NSInteger)component reusingView:(UIView *)view
{
//创建字符变量对象,定义选取器中每一列的数据字符类型字符串
NSString *arrayName = [[NSString alloc] initWithFormat:@"column%d",component+1];
//valueForKey制定其值为arrayName
NSArray *array = [self valueForKey:arrayName];
//返回数组对应的图片
return [array objectAtIndex:row];
}
本文介绍了一个使用UIPickerView控件实现的老虎机游戏案例。通过加载不同的图像资源,演示了如何配置UIPickerView并使其在点击按钮后随机滚动。文章详细展示了创建图像视图、设置UIPickerView的数据源及委托方法的过程。

被折叠的 条评论
为什么被折叠?



