2013-12-11 24 views
2

我有一個UITableView具有固定數量的部分,但每個部分中的行數可能因服務器結果而異。UITableView使用UIPIckerView滾動到特定部分?

我想實現一個選取輪來「跳」到每個部分。這裏是我的UIPickerView委託方法中的UITableViewController:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ 

return 1; 

} 

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ 
return 5; 
} 

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ 
return [self.pickerArray objectAtIndex:row]; 
} 

這是在viewDidLoad中初始化的 「pickerArray」:

self.pickerArray = [[NSArray alloc]initWithObjects:@"Watching", @"Completed", @"On Hold", @"Dropped", @"Planned", nil]; 

,這裏是我的didSelectRow方法:

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{ 
[self.tableView scrollToRowAtIndexPath:[self.pickerArray objectAtIndex:row] atScrollPosition:UITableViewScrollPositionNone animated:YES]; 
} 

我注意到有沒有「scrollTo * 部分 * AtIndexPath」方法,這將是有益的。蘋果的文檔說,這對「indexpath」參數:

indexPath 
An index path that identifies a row in the table view by its row index and its section index. 

調用方法(在選擇器撿東西)拋出此故障:

*終止應用程序由於未捕獲的異常「NSInvalidArgumentException」 ,原因是: ' - [__ NSCFConstantString 節]:無法識別的選擇發送到實例0x4bdb8'

任何想法,我應該做的?

回答

5

scrollToRowAtIndexPath方法將NSIndexPath作爲第一個參數,但代碼傳遞NSString導致異常。

正如文檔所說,NSIndexPath包含一個部分和一個行(因爲您使用部分填充了表視圖,所以您必須知道這一點)。

您需要創建一個NSIndexPath,它對應於表視圖中與在選取器視圖中選擇的row相關的部分的第一行。

所以假設選擇器視圖的row直接對應於你的表視圖的部分:

//"row" below is row selected in the picker view 
NSIndexPath *ip = [NSIndexPath indexPathForRow:0 inSection:row]; 

[self.tableView scrollToRowAtIndexPath:ip 
         atScrollPosition:UITableViewScrollPositionNone 
           animated:YES]; 
+0

謝謝你的幫助。它工作完美。我需要仔細閱讀。 –