今天说说UIPickerView的使用,当然这个API的使用途径一般是商品方向,不多说,直接用代码说话
1:创建UIPickerView对象,设置代理 数据我是直接加载的plist文件,你们根据需求而定
UIPickerView *picker = [[UIPickerViewalloc]initWithFrame:CGRectMake(0, 50, CGRectGetWidth(self.view.frame), 300)];
picker.delegate = self;
picker.dataSource = self;
picker.showsSelectionIndicator = YES;
[self.viewaddSubview:picker];
self.picker = picker;
苹果把许多属性保留为私有的,开放给开发者的少的可怜,可怜到唯一可用的外观选项就是选择窗口, showsSelectionIndicator 属性设置为YES,可以在当前选择上显示一个透明窗口
#pragma mark -----代理方法
//这里返回的是组数,
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
//每组的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if (component == 0) {//第一组作者数据的个数
return self.arr.count;
}else{
//获取对应作者的作品个数 indexOfProvice是一个NSInteger属性值,用于记录选择的第一组数据位置
NSDictionary * dictAtuo =self.arr[self.indexOfProvice];
NSArray * arrName = dictAtuo[@"name"];
return arrName.count;
}
}
//显示数据,相当于tableview中的cell
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if(component == 0){//显示第一组作者的名字
//对应行的作者
NSDictionary * dcit = self.arr[row];
return dcit[@"author"];
}else{
//获取选中的作品,显示作品名字
NSDictionary * dcitName =self.arr[self.indexOfProvice];
NSArray * arrName =dcitName[@"name"];
return arrName[row];
}
}
//选中对应数据,进行操作
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if (component == 0) {
//将选中的作者作标记
self.indexOfProvice = row;
//部份刷新方法 刷新第二组数组 也就是作者对应的作品数据
[pickerView reloadComponent:1];
//让第二组数据每次回到第一行
[pickerView selectRow:0 inComponent:1 animated:YES];
}else{
//获取选中的作品,显示作品名字
NSDictionary * dcitName =self.arr[self.indexOfProvice];
NSArray * arrName =dcitName[@"name"];
self.alertView = [[UIAlertViewalloc]initWithTitle:arrName[row]message:nildelegate:nilcancelButtonTitle:@"取消"otherButtonTitles:@"确定",nil];
[_alertViewshow];
}
}
上图
点击右边时,你可以做一些操作,例如弹框,或者传值