Segue not getting selected row number

后端 未结 3 1704
花落未央
花落未央 2021-02-09 00:37

I am passing data from a table view controller to a detail view. I tried using indexPath.row directly in my prepareForSegue method, however it displays

相关标签:
3条回答
  • 2021-02-09 00:55

    The best way to do this kind of thing is not to use the delegate.

    Updated Swift 4+

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let selectedIndex = tableView.indexPath(for: sender as! UITableViewCell)
        // Do your stuff with selectedIndex.row as the index
    }
    

    Original Answer

    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell)
        // Do your stuff with selectedIndex.row as the index
    }
    
    0 讨论(0)
  • 2021-02-09 00:59
    //In didSelectRowAtIndexPath, you use this code:
    
    func tableView(tvMain: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
            self.performSegueWithIdentifier("yourSegueName", sender: nil)
    
        }
    
    //And prepareForSegue to get IndexPath and send your value
    
    override func prepareForSegue(segue: UIStoryboardSegue,
            sender: AnyObject!){
    
                let indexPath : NSIndexPath = self.yourTableView.indexPathForSelectedRow()!
                //make sure that the segue is going to secondViewController
                let detailsVC = segue.destinationViewController as DetailTableViewController
                detailsVC.selectedPersonName = "\(people[indexPath.row])"
    
        }
    
    0 讨论(0)
  • 2021-02-09 01:00

    Swift 3 update:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let selectedIndex = tableView.indexPath(for: sender as! UITableViewCell)!
        // Do your actual preparing here...
    }
    
    0 讨论(0)
提交回复
热议问题