Reputation: 7569
I want to pass the select row
as indexPath
to the another controller. for that i have write following code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let indexPath = tableView.indexPathForSelectedRow();
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var secondController: SecondViewController = segue.destinationViewController as SecondViewController
secondController.rowIndex.text = indexPath
}
But my indexPath is nil. Why?
Upvotes: 0
Views: 1424
Reputation: 3733
To satisfied your requirement do the following things.
Step 1 : Declare globle variable(that scope is within class).
like var selectedIndexForRow:Int? = nil
var selectedIndexForSection:Int? = nil
Step 2 : Override didSelectRowAtIndexPath
.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedIndexForRow = indexPath.row;
selectedIndexForSection = indexPath.section;
}
Step 3: Pass selectedIndexForRow
and selectedIndexForSection
variables to another controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var secondController: SecondViewController = segue.destinationViewController as SecondViewController
secondController.row= selectedIndexForRow
secondController.section= selectedIndexForSection
}
Upvotes: 0
Reputation: 4271
The sender
here in prepareForSegue
is the UITableViewCell
that you have selected.
Simply typecast it to UITableViewCell
and then call indexPathForCell
on your tableView
. That will return you the indexPath
of the selected cell. No need for additional variables, global or otherwise.
I'm sorry I cannot post any Swift code. I am proficient in Obj-c but I don't know Swift yet.
Sample code for Obj-C is as follows. I hope you'll write the Swift equivalent yourself, or somebody here will edit it in.
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UITableViewCell* cell = (UITableViewCell*)sender;
NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
//Use indexPath as you intend to
}
Upvotes: 0
Reputation: 2093
In cellForRowAtIndexPath , this is wrong:
let indexPath = tableView.indexPathForSelectedRow();
For each row you are saving the selected row in a variable which will be destroyed after cellForRowAtIndexPath finishes, because it is not retained by any object.
You just need this in prepareForSegue
var secondController: SecondViewController = segue.destinationViewController as SecondViewController
if let selectedIndexPath = tableView.indexPathForSelectedRow();
secondController.rowIndex= selectedIndexPath.row
Haven't tested, but think this will work. Hope it helps.
Upvotes: 2