#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
UIPickerView *_pickerView;
// 数据源
NSMutableArray *_arrayM;
// 转动的声音
SystemSoundID _rotationSound;
// 赢得声音
SystemSoundID _winSound;
// 定时器
NSTimer *_timer;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 60, 0, 0)];
_pickerView.dataSource = self;
_pickerView.delegate = self;
[self.view addSubview:_pickerView];
// 添加一个启动按钮
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 400, self.view.frame.size.width, 50)];
btn.backgroundColor = [UIColor lightGrayColor];
[btn setTitle:@"启动" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:30];
[btn addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
// 注册声音
NSString *winPath = [[NSBundle mainBundle] pathForResource:@"win" ofType:@"wav"];
NSURL *url = [NSURL fileURLWithPath:winPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &_winSound);
NSString *rotaionPath = [[NSBundle mainBundle] pathForResource:@"crunch" ofType:@"wav"];
NSURL *rotaionUrl = [NSURL fileURLWithPath:rotaionPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(rotaionUrl), &_rotationSound);
}
- (void)clickButton
{
int count = 1;
int oldRow = -1;
for (int i = 0; i < 5; i ++) {
int row = arc4random() % 6;
[_pickerView selectRow:row inComponent:i animated:YES];
// 播放开始的声音
AudioServicesPlaySystemSound(_rotationSound);
if (row == oldRow) {
count ++;
}else{
count = 1;
}
oldRow = row;
if (count == 3) {
break;
}
}
// 赢
if (count == 3) {
// 播放赢的声音
AudioServicesPlaySystemSound(_winSound);
}
}
#pragma mark -pickerView 数据源方法
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return 6;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 5;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
// 获取复用View
UIImageView *imageView = (UIImageView *)view;
if (!imageView) {
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,100, 60, 50)];
}
NSString *imageName = [NSString stringWithFormat:@"%ld.png",row + 1];
imageView.image = [UIImage imageNamed:imageName];
return imageView;
}
#pragma mark - 设置picker每组的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 70;
}
#pragma mark - 设置picker每组的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
return 60;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
NSLog(@"%ld--%ld",row, component);
}
@end
UIPickerView 选择视图控制器.png
网友评论