2008-10-18 19 views
38

我想在一個UIPickerView組件中顯示一組連續的數字,但它將像Clock-> Timer應用程序的秒組件一樣環繞。我可以啓用的唯一行爲看起來像是Timer應用程序的小時組件,您只能在一個方向上滾動。如何使UIPickerView組件環繞?

回答

44

將行數設置爲很大數量並使其從較高值開始就很容易,用戶很少有機會長時間滾動滾輪 - 即便如此,更糟糕的是他們會觸底。

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { 
    // Near-infinite number of rows. 
    return NSIntegerMax; 
} 

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { 
    // Row n is same as row (n modulo numberItems). 
    return [NSString stringWithFormat:@"%d", row % numberItems]; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.pickerView = [[[UIPickerView alloc] initWithFrame:CGRectZero] autorelease]; 
    // ...set pickerView properties... Look at Apple's UICatalog sample code for a good example. 
    // Set current row to a large value (adjusted to current value if needed). 
    [pickerView selectRow:currentValue+100000 inComponent:0 animated:NO]; 
    [self.view addSubview:pickerView]; 
} 

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { 
    NSInteger actualRow = row % numberItems; 
    // ... 
} 
+0

這對我來說很好!謝謝。 雖然有任何性能/內存問題? – Dimitris 2009-07-20 23:34:55

20

我發現我的答案在這裏:

http://forums.macrumors.com/showthread.php?p=6120638&highlight=UIPickerView#post6120638

當它要求行的標題,給它: 代碼:

return [rows objectAtIndex:(row % [rows count])]; 

當它說用戶didSelectRow:inComponent :,使用像這樣的東西:

代碼:

//we want the selection to always be in the SECOND set (so that it looks like it has stuff before and after) 
if (row < [rows count] || row >= (2 * [rows count])) { 
    row = row % [rows count]; 
    row += [rows count]; 
    [pickerView selectRow:row inComponent:component animated:NO]; 
} 

看來UIPickerView不支持本地包裝,但可以通過插入更多要顯示的數據集並在選擇器停止時將其置於數據集的中間位置來愚弄它。

+0

真棒!萬分感謝 !!好的解決方案真的有幫助 – user1046037 2012-03-21 09:05:00

0

只需多次創建一個數組,以便多次使用您的數字。可以說,當想要從0到23的數字,並把它放在一個數組中。我們會做10次這樣的...

NSString *stdStepper; 

    for (int j = 0; j<10; j++) { 
     for(int i=0; i<24; i++) 
     { 
      stdStepper = [NSString stringWithFormat:@"%d", i]; 

      [_hoursArray addObject:stdStepper]; 

     } 
    } 

後來我們設置選擇這樣

[_hoursPickerView selectRow:120 inComponent:0 animated:NO]; 
0

所有的答案都沒有真正做出選擇器視圖滾動循環的行0。

我做了一個基於UIScrollView的循環tableView。並基於這個tableView,我重新實現了UIPickerView。您可能對此DLPickerView感興趣。這個選擇器視圖具有UIPickerView所具有的所有功能,但也提供了許多新功能,並且定製此選取器視圖更容易。

https://github.com/danleechina/DLPickerView

並且要注意的是這DLPickerView循環滾動真是循環滾動。所有的魔法都是因爲另一個課程DLTableView而發生的。