为什么indexPath.row在这里不起作用?

时间:2016-04-21 12:52:46

标签: ios swift uitableview segue

我将第一个TableView var savedUrls中的值添加到第二个TableView中的var detailsInSection的第一部分。在prepareForSegue中,Xcode显示“indexPath'的未解析标识符。我应该如何修改代码?

在第一个视图控制器中:

var folderNames = [String]()

var savedUrls = [String]()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let url = savedUrls[indexPath.row]

    self.performSegueWithIdentifier(segueToDetailsTable, sender: url)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == segueToDetailsTable {

        let detailsVC = segue.destinationViewController as! DetailsViewController

        detailsVC.detailsInSection[0].append(savedUrls[indexPath.row])

    }   
}

在第二个视图控制器中:

var sectionTitles = ["WebSite", "Date Saved", "Document Used","Add Notes"]

var detailsInSection = [[String]() , [NSDate]() , [AnyObject]() , String]() ]

2 个答案:

答案 0 :(得分:0)

indexPath不是定义或传递到prepareForSegue的变量。你虽然走在正确的轨道上。由于您在url中传递performSegue...作为发件人,因此您无需indexPath来引用url。您可以检查sender是否为String,并使用sender作为所选的url

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let url = savedUrls[indexPath.row]

    self.performSegueWithIdentifier(segueToDetailsTable, sender: url)

}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if let url = sender as? String where segue.identifier == segueToDetailsTable {

        let detailsVC = segue.destinationViewController as! DetailsViewController

        detailsVC.detailsInSection[0].append(url)

    }   
}

答案 1 :(得分:0)

didSelectRow...中的索引路径作为sender参数传递,稍后获取网址

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   self.performSegueWithIdentifier(segueToDetailsTable, sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == segueToDetailsTable {
     let indexPath = sender as! NSIndexPath
     let url = savedUrls[indexPath.row]
     let detailsVC = segue.destinationViewController as! DetailsViewController

     detailsVC.detailsInSection[0].append(url)
  }
}