1、UIPickerView 的创建与设置
- 遵守协议 UIPickerViewDataSource, UIPickerViewDelegate
// 实例化 UIPickerView 对象
UIPickerView *pickerView = [[UIPickerView alloc] init];
// 将 pickerView 添加到屏幕
[self addSubview:pickerView];
// 设置 frame:高度只有三个值:162, 180 和 216,默认为 216,设置为其它的值无效
pickerView.frame = CGRectMake(10, 30, self.width, 162);
// 设置代理
pickerView.dataSource = self;
pickerView.delegate = self;
// 设置默认值
[pickerView selectRow:1 inComponent:0 animated:YES]; // 第 0 列的默认值为 1
[pickerView selectRow:2 inComponent:1 animated:YES]; // 第 1 列的默认值为 2
[pickerView selectRow:3 inComponent:2 animated:YES]; // 第 2 列的默认值为 3
// 设置位置
pickerView.center = self.center;
// 设置背景颜色
pickerView.backgroundColor = [UIColor orangeColor];
// 是否显示指示器:default is NO
pickerView.showsSelectionIndicator = YES;
// 刷新指定的列
[pickerView reloadComponent:0];
// 刷新所有的列
[pickerView reloadAllComponents];
// 获取列数,只读
NSInteger numberOfComponents = pickerView.numberOfComponents;
// 获取指定列的行数
NSInteger numberOfRows = [pickerView numberOfRowsInComponent:0];
// 获取指定行的尺寸
CGSize rowSize = [pickerView rowSizeForComponent:0];
// 获取指定列被选中的行数索引
NSInteger selectedIndex = [pickerView selectedRowInComponent:0];
// 获取指定行列的视图
UIView *view = [pickerView viewForRow:3 forComponent:0];
2、UIPickerViewDataSource 协议方法
// 设置列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 3;
}
// 设置行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return 10;
}
// 设置各行内容为 字符串
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return @"123456789";
}
// 设置各行内容为 NSAttributedString 型字符串
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
}
// 设置列宽:不设置时为默认宽度,UIPickerViewDelegate 方法
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
return 50;
}
// 设置行高:不设置时为默认高度 32,UIPickerViewDelegate 方法
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
return 50;
}
// 设置各行内容为 view
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
return [[UIView alloc] init];
}
// 检测行的选择状态,在滑动停止后触发
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
}