UITableView scroll to specific section using UIPIckerView?

扶醉桌前 提交于 2020-01-04 17:45:48

问题


I have a UITableView that has a fixed number of sections, however the number of rows in each section can vary depending on server results.

I would like to implement a picker wheel to "jump" to each section. Here are my UIPickerView delegate methods in the 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];
}

The "pickerArray" which is initialized in ViewDidLoad:

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

and here's my didSelectRow method:

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

I noticed there's no "scrollTo*section*AtIndexPath" method, which would be helpful. Apple's docs say this about the "indexpath" parameter:

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

Calling the method (picking something in the picker) throws this fault:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString section]: unrecognized selector sent to instance 0x4bdb8'

Any idea what I should be doing?


回答1:


The scrollToRowAtIndexPath method takes an NSIndexPath as the first parameter but the code is passing an NSString resulting in the exception.

As the docs say, an NSIndexPath includes both a section and row (you must know this since you populated a table view with sections).

You need to create an NSIndexPath that corresponds to the first row of the section in the table view that relates to the row selected in the picker view.

So assuming that the row of the picker view corresponds directly to the sections in your table view:

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

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


来源:https://stackoverflow.com/questions/20508752/uitableview-scroll-to-specific-section-using-uipickerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!