我的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
所以我不认为它被称为。
您的发件人是UIButton
的新实例,它没有您需要的任何信息。而是通过调用选择器的按钮。
@objc func displayStatDetail(_ sender: StatisticButton) {
self.performSegue(withIdentifier: "StatDetailSegue", sender: sender)
}
您需要在循环中更改目标选择器。
statisticButton.addTarget(self, action: #selector(displayStatDetail(_:)), for: .touchUpInside)
你在这里传递UIButton
的新实例作为sender
:
self.performSegue(withIdentifier: "StatDetailSegue", sender: UIButton())
相反,你应该在那里有你的statisticButton
。您的按钮目标选择器方法可以有一个参数 - 用户单击的按钮实例。用它作为sender
。
你在performSegue
function中有一个错误,你总是发送一个UIButton的新对象,而不是你点击过的那个。这是你应该做的。
statisticButton.addTarget(self, action: #selector(displayStatDetail(_ :)), for: .touchUpInside)
@objc func displayStatDetail(_ sender: UIButton) {
self.performSegue(withIdentifier: "StatDetailSegue", sender: sender)
}