我将数据从表视图控制器传递到详细信息视图.我尝试在prepareForSegue方法中直接使用indexPath.row,但它显示错误
use of unresolved identifier ‘indexPath’
因此,在搜索Web之后,我设置了变量indexOfSelectedPerson,该变量被赋予indexPath.row的值.我在模拟器中运行应用程序时的问题是prepareForSegue获取indexOfSelectedPerson(0)的初始值,然后在我单击它之后获取所选行的值.因此,当我点击模拟器中的后退按钮并选择另一行时,详细视图会显示我上一次选择的行的信息.
import UIKit class MasterTableViewController: UITableViewController { var people = [] var indexOfSelectedPerson = 0 override func viewDidLoad() { super.viewDidLoad() people = ["Bob","Doug","Jill"] } override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { return 1 } override func tableView(tableView: UITableView?,numberOfRowsInSection section: Int) -> Int { return people.count } override func tableView(tableView: UITableView!,cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView!.dequeueReusableCellWithIdentifier("personCell",forIndexPath: indexPath) as UITableViewCell cell.text = "\(people[indexPath.row])" return cell } override func tableView(tableView: UITableView!,didSelectRowAtIndexPath indexPath: NSIndexPath!) { indexOfSelectedPerson = indexPath.row } override func prepareForSegue(segue: UIStoryboardSegue!,sender: AnyObject!) { if let mySegue = segue.identifier { if mySegue == "personDetails" { let detailsVC: DetailTableViewController = segue.destinationViewController as DetailTableViewController detailsVC.selectedPersonName = "\(people[indexOfSelectedPerson])" } } } }
因此,当应用程序首次在模拟器中启动时选择Doug会显示Bob的详细信息,因为indexPathOfSelectedPerson为0.按下后退按钮然后选择Jill会显示Doug的详细信息,因为当我上一次单击Doug时indexPathOfSelectedPerson变为1.我猜测问题源于调用方法的顺序.
做这种事情的最好方法是不使用委托.
override func prepareForSegue(segue: UIStoryboardSegue!,sender: AnyObject!) { let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell) // Do your stuff with selectedIndex.row as the index }