- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Action"])
{
NSIndexPath *indexPath = [self.tbl indexPathForSelectedRow];
SecondViewController *destViewController = segue.destinationViewController;
destViewController.getString = [getArray objectAtIndex:indexPath.row];
}
}
我想访问所选行index
,但为每个选定行显示null
。请帮帮我?
答案 0 :(得分:67)
两种情况:
1)Segue
从viewController
从segue
方法拨打didSelectRowAtIndexPath
,将indexPath
作为sender
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:@"Action" sender:indexPath];
}
然后,您可以在prepareForSegue:sender:
方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Action"])
{
NSIndexPath *indexPath = (NSIndexPath *)sender;
SecondViewController *destViewController = segue.destinationViewController;
destViewController.getString = [getArray objectAtIndex:indexPath.row];
}
}
2)从细胞连接的segue
无需实施didSelectRowAtIndexPath
方法和performSegueWithIdentifier:
。您可以在sender
方法中直接获取UITableviewCell
prepareForSegue:sender:
。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Action"])
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
SecondViewController *destViewController = segue.destinationViewController;
destViewController.getString = [getArray objectAtIndex:indexPath.row];
}
}
答案 1 :(得分:50)
Swift 3.0 / iOS 10
在iOS 9中引入了 tableView.indexPathForSelectedRow
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = tableView.indexPathForSelectedRow{
let selectedRow = indexPath.row
let detailVC = segue.destination as! ParkDetailTableVC
detailVC.park = self.parksArray[selectedRow]
}
}
答案 2 :(得分:4)
喜欢这个
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender {
FTGDetailVC *detailVC = (id)segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
FTGNote *note = self.notes[indexPath.row];
[detailVC updateWithNote:note];
}
答案 3 :(得分:0)
indexPath.row
的{{1}}方法获取UITAbleViewDelegate
:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
self.myVariable = indexPath.row
}
然后您可以通过以下方式访问prepareForSegue
中的此值:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//do something with self.myVariable
}
我希望我帮助过你。