UIPickerView官方描述:
A view that uses a spinning-wheel or slot-machine metaphor to show one or more sets of values.
A picker view displays one or more wheels that the user manipulates to select items. Each wheel—known as a component—has a series of indexed rows representing the selectable items. Each row displays a string or view so that the user can identify the item on that row. Users select items by rotating the wheels to the desired values, which align with a selection indicator.
译文:
使用旋转轮或狭缝机隐喻显示一组或多组值的视图。
选取器视图显示用户操纵选择项目的一个或多个轮子。每个车轮(称为组件)都有一系列代表可选项目的索引行。每行显示一个字符串或视图,以便用户可以识别该行上的项目。用户通过将车轮旋转到与选择指示符对齐的期望值来选择项目。
下面开始UIPickerView学习:
查看UIPickerView类中的.h文件
UIPickerView父类是UIView;
1 | NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UIPickerView : UIView <NSCoding> |
属性
1,显示选中指示器,目前设置为NO或者为YES都没有什么影响;
1 | @property(nonatomic)BOOL showsSelectionIndicator; |
2,当前UIPickerView的component数,为只读属性;
1 | @property(nonatomic,readonly) NSInteger numberOfComponents; |
方法
1,获取某一个component的行数:
1 | - (NSInteger)numberOfRowsInComponent:(NSInteger)component; |
2,获取某个component行的size大小:
1 | - (CGSize)rowSizeForComponent:(NSInteger)component; |
3,返回一个view,来自协议方法:pickerView:viewForRow:forComponent:reusingView:
1 | // returns the view provided by the delegate via pickerView:viewForRow:forComponent:reusingView: |
4,刷新所有component和单个component:
1 | - (void)reloadAllComponents;//刷新所有component |
5,滑动到某个component的某行,animated表示是否要动画效果:
1 | - (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated; |
6,获取当前选中的行, -1 if nothing selected:
1 | - (NSInteger)selectedRowInComponent:(NSInteger)component; |
实现的2个协议: UIPickerViewDataSource,UIPickerViewDelegate
1 | @property(nullable,nonatomic,weak) id<UIPickerViewDataSource> dataSource; // default is nil. weak reference |
1,UIPickerViewDataSource
1 | @required //表示下面协议方法必须实现 |
2,UIPickerViewDelegate,由@optional进行修饰,表示该协议下的方法可以选择性的实现:
2.1,设置component的宽和高
1 | // returns width of column and height of row for each component. |
2.2,返回每一行的展示数据,数据类型是:NSString或者是NSAttributedString
1 | - (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component __TVOS_PROHIBITED; |
2.3,每一个component行数中的view,可以进行自定义:但必须是UILabel
1 | - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view __TVOS_PROHIBITED; |
2.4,当前选中的component和row
1 | - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component __TVOS_PROHIBITED; |
代码示例
默认大小
1,当UIPickerView没有设置frame值时,默认宽是320,高是216;