我正在将数据从表视图控制器传递到详细视图。我尝试使用indexPath.row
直接在我的prepareForSegue
方法,但是它显示错误
使用未解析的标识符“indexPath”
因此,在搜索网络后,我设置了变量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 的详细信息,因为indexPathOfSelectedPerson
当我上次点击 Doug 时,变成了 1。我猜测问题源于方法的调用顺序。
做这种事情的最好方法是不使用委托。
更新了斯威夫特 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
}
原答案
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
let selectedIndex = self.tableView.indexPathForCell(sender as UITableViewCell)
// Do your stuff with selectedIndex.row as the index
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)