UITableView-IndexPath始终始终首先返回0&只需点击两次,即可将正确的数据传递给视图控制器 [英] UITableView - IndexPath always returns 0 first & takes 2 clicks to pass correct data to view controller
问题描述
我有一个 UITableView
,可以选择 ViewController
.我的tableview包含一个位置名称列表,当您选择一个位置时,它将有关选定位置的更详细的数据传递给视图控制器.我的问题是,无论我单击哪一行,索引路径在第一次单击/加载时始终返回0.我必须单击每一行两次,以便它传递正确的数据.
I have a UITableView
that segues to a ViewController
. My tableview contains a list of location names and when you select a location, it passes more detailed data to the view controller about the selected location. My issue is that my index path always returns 0 on the first click / load no matter which row I click. I have to click each row twice for it pass the right data.
示例:我点击第2行>返回第1行的(0)数据.然后,我再次单击row2>正确返回row2的数据>然后单击row3>返回row2的数据>我必须再次单击row3以获得row3的数据.以下代码中的 indexPathSelected
在加载时始终为 0
.
Example: I click row2 > returns row1's (0) data. I then click row2 again > correctly returns row2's data > I then click row3 > returns row2's data > I have to click row3 again to get row3's data. indexPathSelected
in the below code is always 0
on load.
NSInteger indexPathSelected;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
indexPathSelected = indexPath.row;
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showLocationDetails"])
{
LocationDetailsViewController *vc = [segue destinationViewController];
vc.location = _locationsArray [indexPathSelected];
}
}
推荐答案
问题是在didSelectRowAtIndexPath之前调用了prepareForSegue.使用segues时,通常根本不需要实现didSelectRowAtIndexPath.prepareForSegue:sender:中的sender参数是您选择的单元格,因此您可以从中获取索引路径:
The problem is that prepareForSegue is called before didSelectRowAtIndexPath. When using segues, it's not usually necessary to implement didSelectRowAtIndexPath at all. The sender argument in prepareForSegue:sender: is the cell you selected,, so you can get the index path from it:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showLocationDetails"])
{
LocationDetailsViewController *vc = [segue destinationViewController];
indexPathSelected = [self.tableView indexPathForCell:sender].row;
vc.location = _locationsArray[indexPathSelected];
}
}
这篇关于UITableView-IndexPath始终始终首先返回0&只需点击两次,即可将正确的数据传递给视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!