为 Segue 函数未正确传递数据做准备

Prepare for Segue function not passing data correctly

我的 prepareForSegue 方法没有将数据传递到目标视图控制器。

var buttonsDictionary = [Int: UIButton]()

func createButtonArray() {
    for item in statTitles {
        let statisticButton = StatButton()

        statisticButton.layer.cornerRadius = 10
        statisticButton.backgroundColor = UIColor.darkGray
        statisticButton.setTitle(String(item.value), for: UIControlState.normal)
        statisticButton.setTitleColor(UIColor.white, for: UIControlState.normal)
        statisticButton.titleLabel?.font = UIFont.systemFont(ofSize: 43)
        statisticButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
        statisticButton.contentHorizontalAlignment = .left

        statisticButton.addTarget(self, action: #selector(displayStatDetail), for: .touchUpInside)

        statisticButton.buttonIndex = item.key

        buttonsDictionary[item.key] = (statisticButton) //  Assign value at item.key

        print(statisticButton.buttonIndex)
    }
}

func viewSavedStatistics() {
    for button in buttonsDictionary {
        statisticsView.addArrangedSubview(button.value)
    }
}

@objc func displayStatDetail() {
    self.performSegue(withIdentifier: "StatDetailSegue", sender: UIButton())
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "StatDetailSegue" {
        if let destinationVC = segue.destination as? StatDetailViewController,
            let index = (sender as? StatButton)?.buttonIndex {
            destinationVC.statID = index
            print("Destination STATID: \(destinationVC.statID)")
        }
    }
}

以上代码全部写在ViewControllerclass中。 StatButton 是自定义 UIButton class。 prepare 意味着传递点击按钮的 buttonIndex,但只传递 0 而不会传递 print,所以我不认为它被调用了。

您在此处将 UIButton 的新实例作为 sender 传递:

self.performSegue(withIdentifier: "StatDetailSegue", sender: UIButton())

相反,您应该 statisticButton 在那里。您的按钮目标选择器方法可以有一个参数 - 用户单击的按钮实例。将其用作 sender.

您的发件人是 UIButtonnew 实例,没有您需要的任何信息。而是传递调用选择器的按钮。

@objc func displayStatDetail(_ sender: StatisticButton) {
    self.performSegue(withIdentifier: "StatDetailSegue", sender: sender)
}

您需要像这样在循环中更改目标选择器。

statisticButton.addTarget(self, action: #selector(displayStatDetail(_:)), for: .touchUpInside)

您在 performSegue函数中有一个错误,您总是发送一个新的 UIButton 对象,而不是您单击的对象。这是你应该做的。

 statisticButton.addTarget(self, action: #selector(displayStatDetail(_ :)), for: .touchUpInside)

@objc func displayStatDetail(_ sender: UIButton) {
    self.performSegue(withIdentifier: "StatDetailSegue", sender: sender)
}