- 父类是UIView
使用场景:通常在注册模块,当用户需要选择一些东西的时候,比如说城市,往往弹出一个PickerView给他们选择。
-
老虎机效果:
UIPickViewios6和ios7.png 使用时需要设置代理,让代理实现相关功能
UIPickerView所有属性
// 数据源代理
pickerView.dataSource = self;
// UIPickerViewDelegate代理
pickerView.delegate = self;
// 是否显示选择指示器,默认为NO
pickerView.showsSelectionIndicator = NO;
// 获取组数,只读
NSInteger index = pickerView.numberOfComponents;
UIPickerView所有方法
// 设置某组某行的视图
- (nullable UIView *)viewForRow:(NSInteger)row forComponent:(NSInteger)component
{
// 控件创建
// 返回控件
}
// 更新所有组或某组的数据
[ pickerView reloadAllComponents];
[ pickerView reloadAllComponents:3];
//选中第几组第几行
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
{
// 选中后要实现的代码
}
// 返回在选中的组中的第几行,没有选中则返回-1
- (NSInteger)selectedRowInComponent:(NSInteger)component
{
return 10;
}
如何让UIPickerView展示数据
跟UITableView类似
- 设置数据源对象
pickerView.dataSource = self;
- 数据源对象要遵守数据源协议
@interface ViewController () <UIPickerViewDataSource>
- 实现数据源方法
// 返回有多少部分 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 5; } // 返回第component有多少行 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { return 10; }
UIPickerViewDelegate
// 返回第component列多宽
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
return 50;
}
// 返回第component列多高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return 50;
}
// 返回第component列第row行标题
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return @"行标题";
}
// NSAttributedString:富文本,可以描述文本的外观属性,颜色,字体,阴影,空心,图文混排
//- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
// 返回富文本字符串
}
// 返回第component列第row行视图控件
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
return [UISwitch alloc] init];
}
// 当用户选中某一行的时候调用
// 选中第component列第row行的时候调用
// 可以监听pickerView滚动
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// 选中时代码
}