准备Segue函数无法正确传递数据

时间:2018-09-02 07:14:10

标签: ios swift uistoryboardsegue

我的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)")
        }
    }
}

以上所有代码都写在ViewController类中。 StatButton是一个自定义UIButton类。 准备是指在点击的按钮buttonIndex上传递,但仅传递0而不传递print,因此我不认为它被调用。

3 个答案:

答案 0 :(得分:0)

您要在此处传递UIButton的新sender实例:

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

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

答案 1 :(得分:0)

您的发件人是UIButton new 实例,它没有您需要的任何信息。而是通过按钮调用选择器。

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

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

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

答案 2 :(得分:0)

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

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

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