由於UIPickerView默認並不提供數據的循環顯示方法,而我們平時有時候會有需求要求Picker中的數據循環顯示,所以我們只能在數據源上面動手腳。
主要需要處理的有以下幾個地方:
(轉載請保留此文字:本文來源:[ios開發技巧之]UIPickerView的數據循環顯示 http://blog.csdn.net/ipromiseu/article/details/7436521]
,write by Gray.Luo,接受ios/android app 外包開發: [email protected] )
1.UIPickerView的數據源中的行數,我們需要設置一個讓用戶可以接受的行數 ,也不至於讓picker的數據過多而影響拖動效果,比如16384等,讓用戶看起來是循環顯示的效果,當然實際上並不是循環顯示,但是這完全可以滿足要求:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return 16384;
}
2.修改每一行的數據獲取的方式,其實就是對我們的數據源數組進行取模而以:
-(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
//NSLog(@"start : row %d component %d", row, component);
int fontSize = 36;
CGRect rect = CGRectMake(0.0, 0.0, 200, 50);
if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
rect = CGRectMake(0.0, 0.0, 200, 50);
fontSize = 36;
}else {
rect = CGRectMake(0.0, 0.0, 100, 50);
fontSize = 14;
}
UILabel *myView = [[[UILabel alloc] initWithFrame:rect] autorelease];
myView.textAlignment = UITextAlignmentCenter;
myView.font = [UIFont boldSystemFontOfSize:fontSize];
myView.backgroundColor = [UIColor clearColor];
myView.text = [tmpArray objectAtIndex:row % [tmpArray count]];
// NSLog(@"end:row %d component %d,content:%@", row, component,myView.text );
return myView;
}
3.第三個就是初始化的時候,讓每一列都跳到上面的最大行數的中間,讓用戶感覺數據是循環的。
- (void)viewDidLoad {
[super viewDidLoad];
for (int i = 0; i < 6; i++) {
[pickerView selectRow:16384/2 inComponent:i animated:NO];
}
}
4.最後一點就是取數據,我們還是按上面的數據源的取值方法一樣:
- (IBAction)queryButtonHandle{
NSLog(@"weightArray:%d",[pickerView selectedRowInComponent:0]%[weightArray count]);
NSLog(@"colorArray:%d",[pickerView selectedRowInComponent:1]%[colorArray count]);
NSLog(@"cleanLevelArray:%d",[pickerView selectedRowInComponent:2]%[cleanLevelArray count]);
NSLog(@"cutType1Array:%d",[pickerView selectedRowInComponent:3]%[cutType1Array count]);
NSLog(@"cutType2Array:%d",[pickerView selectedRowInComponent:4]%[cutType2Array count]);
NSLog(@"cutType3Array:%d",[pickerView selectedRowInComponent:5]%[cutType3Array count]);
}
參考:http://www.timespace.org/2008/07/11/the-abusive-pickerview/