gpt4 book ai didi

Swift - Unwind segue 传回零值?

转载 作者:行者123 更新时间:2023-11-28 06:36:36 25 4
gpt4 key购买 nike

我有两个 View Controller 。第二个 View Controller 承载一个带有自定义单元格的 TableView ,该单元格展开回第一个 View Controller 并发回与该单元格关联的数据。

在第二个 View Controller 类中,我实现了 didSelectRowAtIndexPath 并进行了测试以查看正确的项目是否存储在类属性中。它正确地存储了可选值,但是当我尝试在第一个 View Controller 中使用该值时,该属性将 nil 打印到控制台。

// First view controller

@IBAction func unwindActivitiesVCCellTapped( segue: UIStoryboardSegue )
{
// table view cell tapped

guard let activitiesVC = segue.sourceViewController as? ActivitiesVC else { return }

print(activitiesVC.activityPerforming) // Displays nil in console output

if let activityPerforming = activitiesVC.activityPerforming // thus this does not get called
{
activityPerformingButton.titleLabel?.text = activityPerforming
}
}

// Second View Controller

class ActivitiesVC: UIViewController
{
@IBOutlet weak var activitiesTableView: UITableView!

let activityTitles = [ "Walk" , "Run ", "Cycle", "Mountain Bike" ]

var activityPerforming: String?

override func viewDidLoad()
{
super.viewDidLoad()

activitiesTableView.dataSource = self
activitiesTableView.delegate = self
}
}

extension ActivitiesVC: UITableViewDelegate
{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
activityPerforming = activityTitles[ indexPath.row ]
print(activityPerfoming) // displays optional value I want
}
}

// Custom Cell

class ActivityCell: UITableViewCell
{

@IBOutlet weak var imageLabel : UILabel!
@IBOutlet weak var activityLabel : UILabel!

override func awakeFromNib()
{
super.awakeFromNib()
// Initialization code
}

override func setSelected(selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}
}

属性显示为 nil 的原因是什么?我该怎么做才能补救这种情况?

最佳答案

我怀疑你的 unwind segue 直接连接到你的 UITableViewCell 所以它在 didSelectRowAtIndexPath 被调用之前被触发。

要解决此问题,请将 didSelectRowAtIndexPath 中的代码移动到 prepareForSegue 中:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let indexPath = activitiesTableView.indexPathForSelectedRow {
activityPerforming = activityTitles[ indexPath.row ]
print(activityPerfoming) // displays optional value I want
}
}

关于Swift - Unwind segue 传回零值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935949/

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