UIPickerView的使用
UIPickerView的基本概念
UIPickerView是一个选择器控件,可以生成单列/多列的选择器,UIPickerView直接继承UIView,他不能像UIcontrol绑定事件处理方法,需要由代理对象来处理事件
UIPickerView的创建
UIPickerView* pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(20, 100, 280, 100)];
UIPickerView的属性
获取属性
- 获取分区数量
@property(nonatomic,readonly) NSInteger numberOfComponents;
- 获取分区的行数
- (NSInteger)numberOfRowsInComponent:(NSInteger)component;
- 获取行的尺寸(CGSize)
- (CGSize)rowSizeForComponent:(NSInteger)component;
- 获取某一分区某一行的视图
- (nullable UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component;
设置属性
- 刷新分区
- (void)reloadAllComponents;
- 刷新指定分区
- (void)reloadComponent:(NSInteger)component;
- 选中某一分区的某一行
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated;
- 选中某一分区
- (NSInteger)selectedRowInComponent:(NSInteger)component;
代理
- UIPickerViewDataSource
@protocol UIPickerViewDataSource<NSObject>
@required // 必须实现的
// returns the number of 'columns' to display.
// 设置分区数量
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
// returns the # of rows in each component..
// 设置分区有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
@end
- UIPickerViewDelegate
@protocol UIPickerViewDelegate<NSObject>
@optional
// 返回每个组件的列宽和行高。
// 设置某一分区的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component API_UNAVAILABLE(tvos);
// 设置分区里行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component API_UNAVAILABLE(tvos);
// 这些方法返回普通NSString、NSAttributedString或视图(例如UILabel)以显示组件的行。
// 对于视图版本,我们缓存所有隐藏的、因此未使用的视图,并将其传递回以供重用。
// 如果返回不同的对象,旧对象将被释放。视图将以行矩形为中心
// 设置行的标题
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component API_UNAVAILABLE(tvos);
// 设置行的标题为属性字符串(NSAttributedString)
- (nullable NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component API_AVAILABLE(ios(6.0)) API_UNAVAILABLE(tvos); // 如果两种方法都实现了,则倾向于使用属性化标题
// 设置行为一个视图
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view API_UNAVAILABLE(tvos);
// 选中某一行的时候回调的方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component API_UNAVAILABLE(tvos);
@end