在iOS实际项目中,常常会出现界面中多个地方须要使用UIPickerView,若是在每一个须要用到的地方都建立一个UIPickerView不只更耗性能,并且还会让你的代码变得更加杂乱、冗余,所以我在这里向你们介绍一下我对UIPickerView的一些简单封装。数组
/** pickerView*/
@property (nonatomic, strong) UIPickerView pickerView;
/* pickerView背景*/
@property (nonatomic, strong) UIView pickerBackGroundView;
/* 背景*/
@property (nonatomic, strong) UIView backGroundView;
/* 确认按钮*/
@property (nonatomic, strong) UIButton sureButton;
/* 取消按钮*/
@property (nonatomic, strong) UIButton cancelButton;
/* 单列pickerView*/
@property (nonatomic, strong) NSMutableArray slDataArray;
/* 双列pickerView*/
@property (nonatomic, strong) NSMutableArray *mulDataArray;
ide
若是只须要一列的话,只须要传入一个数据数组:slDataArray,若是须要两行,则两个数组都须要赋值。性能
-(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,不然加载一列。atom
-(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初始化是让其选中哪行,第二个则是两列的选择方法。component
-(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;
}];
}
}
}
rem
这个方法是显示或者隐藏pickerView,经过动画的方式,背景慢慢变黑或者透明,pickerView从下往上出现或者从上往下消失。animation
-(void)pickerViewReloadData{
[self.pickerView reloadAllComponents];
}
it
刷新pickerView数据,加载另外一个pickerView时,调用该方法刷新。