gpt4 book ai didi

swift - 如何访问 prepareForSegue 中选定单元格的数据

转载 作者:搜寻专家 更新时间:2023-11-01 06:23:16 25 4
gpt4 key购买 nike

我正在尝试创建我的第一个 segue,我想将数据从我选择的 tableViewCell 传递到我要 segue 的辅助 View Controller 。

我的问题是:

由于 prepareForSegue 不采用 indexPath,我如何获取有关我选择的特定单元格的信息?

这是我的应用程序的照片,里面有一些虚拟数据,右边带箭头的单元格代表我要从中提取的单元格:

enter image description here

这是我的 CustomCell 类,这些行派生自:

TimingCell.swift

class TimingCell: UITableViewCell {

@IBOutlet weak var timingLabel: UILabel!
@IBOutlet weak var timeSetLabel: UILabel!

...
}

这里是我设置 segue 方法的地方:

ViewController.Swift

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, SettingCellDelegate {


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


var view: TimeViewController = segue.destinationViewController as! TimeViewController


}

*如果您需要在下面的评论中查看更多代码,请告诉我

最佳答案

所以你应该从 UITableViewController 开始,而不仅仅是 View Controller 。

在 UITableViewController 中,您需要覆盖:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.

return 6 //Looks like you have six rows in your TableView
}

现在您需要一个类作用域的 NSIndexPath 变量来跟踪所选行的索引,因此要创建该变量:

var path = NSIndexPath()

现在您还需要两个重写,第一个是在选择行时设置路径变量,第二个是在您选择行后取消选择该行(确保当您从 subview Controller ):

override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath : NSIndexPath) -> NSIndexPath? {
path = indexPath
return indexPath
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(path, animated: true)
}

最后,在您的 prepareForSegue 函数中,您可以使用路径变量来确定选择了哪一行并相应地设置 subview Controller 变量:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var dest = segue.destinationViewController as! TimeViewController
if path == 1 {
//set some destination variables here
} else {
//or here
}
}

如果你有一个数据结构,你可以从中确定 TableView 中的每一行将包含什么,只需使用路径作为数据结构的索引,并将该行的信息传递给目标 View Controller 。例如,像这样的东西:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var dest = segue.destinationViewController as! TimeViewController
dest.rowTitle = myRowsArray[path.row].title
}

表格 View 有点习惯......祝你好运!

关于swift - 如何访问 prepareForSegue 中选定单元格的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29598074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com