本帖最后由 竹林风 于 2018-12-8 18:00 编辑
文章导航
介绍
UIPickerView是一个选择器控件,可以生成单列的选择器,也可生成多列的选择器,而且开发者完全可以自定义选择项的外观,因此用法非常灵活。
1.单个pickerview的使用
[Objective-C] 纯文本查看 复制代码 #import "firstVC.h"
@interface firstVC ()<UIPickerViewDataSource,UIPickerViewDelegate> //遵循协议
@property (nonatomic,strong)UIPickerView * pickerView;//自定义pickerview
@property (nonatomic,strong)NSArray * letter;//保存要展示的字母
@property (nonatomic,strong)NSArray * number;//保存要展示的数字
@end
@implementation firstVC
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
self.title = @"Leader";
//获取需要展示的数据
[self loadData];
// 初始化pickerView
self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 50, self.view.bounds.size.width, 200)];
[self.view addSubview:self.pickerView];
//指定数据源和委托
self.pickerView.delegate = self;
self.pickerView.dataSource = self;
}
#pragma mark 加载数据
-(void)loadData
{
//需要展示的数据以数组的形式保存
self.letter = @[@"aaa",@"bbb",@"ccc",@"ddd"];
self.number = @[@"111",@"222",@"333",@"444"];
}
#pragma mark UIPickerView DataSource Method 数据源方法
//指定pickerview有几个表盘
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;//第一个展示字母、第二个展示数字
}
//指定每个表盘上有几行数据
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
NSInteger result = 0;
switch (component) {
case 0:
result = self.letter.count;//根据数组的元素个数返回几行数据
break;
case 1:
result = self.number.count;
break;
default:
break;
}
return result;
}
#pragma mark UIPickerView Delegate Method 代理方法
//指定每行如何展示数据(此处和tableview类似)
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString * title = nil;
switch (component) {
case 0:
title = self.letter[row];
break;
case 1:
title = self.number[row];
break;
default:
break;
}
return title;
}
看效果:
附件:
Test-UIPickerView.zip
(199.47 KB, 下载次数: 0)
|