iOS UIPickerView的简单封装示例
前言
在iOS实际项目中,经常会出现界面中多个地方需要使用UIPickerView,如果在每个需要用到的地方都创建一个UIPickerView不仅更耗性能,而且还会让你的代码变得更加杂乱、冗余,因此我在这里向大家介绍一下我对UIPickerView的一些简单封装。
所需属性
/** pickerView*/
@property (nonatomic, span) UIPickerView pickerView;
/* pickerView背景*/
@property (nonatomic, span) UIView pickerBackGroundView;
/* 背景*/
@property (nonatomic, span) UIView backGroundView;
/* 确认按钮*/
@property (nonatomic, span) UIButton sureButton;
/* 取消按钮*/
@property (nonatomic, span) UIButton cancelButton;
/* 单列pickerView*/
@property (nonatomic, span) NSMutableArray slDataArray;
/* 双列pickerView*/
@property (nonatomic, span) NSMutableArray *mulDataArray;
如果只需要一列的话,只需要传入一个数据数组:slDataArray,如果需要两行,则两个数组都需要赋值。
实现UIPickerView代理方法
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
if (self.mulDataArray.count == 0) {
return 1;
}else {
return 2;
}
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if (component == 0) {
return self.slDataArray.count;
}else {
return self.mulDataArray.count;
}
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0) {
return self.slDataArray[row];
}else {
return self.mulDataArray[row];
}
}
这里根据两个数组来初始化pickerView的内容,即判断第二个数组(mulDataArray)是否有数据,有数据的话代表加载两列的pickerView,否则加载一列。
功能实现
-(void)pickerViewSelectRow:(NSInteger)row
{
self.selectRow = row;
[self.pickerView selectRow:row inComponent:0 animated:NO];
}
-(void)pickerViewSelectRow:(NSInteger)row lastRow:(NSInteger)lastRow{
[self.pickerView selectRow:row inComponent:0 animated:NO];
[self.pickerView selectRow:lastRow inComponent:1 animated:NO];
}
第一个方法是只有一列的pickerView初始化是让其选中哪行,第二个则是两列的选择方法。
-(void)showOrHidePickerView:(BOOL)isShow{
if (isShow) {
if (self.isPickerShow == NO) {
[self addSubview:self.backGroundView];
[self addSubview:self.pickerBackGroundView];
[UIView animateWithDuration:0.3 animations:^{
self.backGroundView.alpha = 0.5;
self.pickerBackGroundView.frame = CGRectMake(0, SCREEN_HEIGHT -220, SCREEN_WIDTH, 220);
} completion:^(BOOL finished) { self.isPickerShow = YES;
}];
}
}else {
if (self.isPickerShow) {
[UIView animateWithDuration:0.3 animations:^{
self.backGroundView.alpha = 0.0;
self.pickerBackGroundView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 220);
} completion:^(BOOL finished) {
[self.backGroundView removeFromSuperview];
[self.pickerBackGroundView removeFromSuperview];
self.isPickerShow = NO;
}];
}
}
}
这个方法是显示或者隐藏pickerView,通过动画的方式,背景慢慢变黑或者透明,pickerView从下往上出现或者从上往下消失。
-(void)pickerViewReloadData{
[self.pickerView reloadAllComponents];
}
刷新pickerView数据,加载另一个pickerView时,调用该方法刷新。
总结
以上是 iOS UIPickerView的简单封装示例 的全部内容, 来源链接: utcz.com/z/323784.html