![](/img/trans.png)
[英]When the button in TableView cell pressed, how do I know the button of which row of cell pressed?
[英]How do I know in swift which button was pressed when different buttons lead to the same ViewController?
我有四個按鈕,它們都通向相同的視圖 controller。 我需要知道按下了哪個按鈕,因為每個按鈕的視圖 controller 設置略有不同。 我嘗試了以下操作:ViewController(稱為“SecondViewController”),其中一個按鈕被按下
var index = 0
@IBAction func Button1(_ sender: UIButton) {
index = 1
}
@IBAction func Button2(_ sender: UIButton) {
index = 2
}
@IBAction func Button3(_ sender: UIButton) {
index = 3
}
@IBAction func Button4(_ sender: UIButton) {
index = 4
}
func getIndex() -> Int{
return index
}
之后打開的視圖 controller
// to get functions from SecondViewController
var second = SecondViewController()
let index = second.getIndex()
print(index)
不幸的是,它總是打印零。 我猜是因為我在開始時將索引設置為 0,但我不明白為什么按下按鈕時值不更新。
我能做些什么?
我猜你正在使用 segue,所以你的 segue 在你的 IBAction 可以更新你的索引值之前執行。 這里有一個類似的問題和解決方案
因此,要解決此問題,請為您的 segue 提供一個標識符,並從您的 IBAction 方法中調用performSegueWithIdentifier
。
SecondViewController(前一個包含按鈕)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let firstViewController = segue.destination as? FirstViewController {
firstViewController.index = self.index
}
}
FirstViewController(單擊按鈕后應顯示一個)
var index: Int?
override func viewDidLoad() {
super.viewDidLoad()
print(index)
}
如果我理解正確,你肯定會得到索引為 0。
var index = 0
@IBAction func Button1(_ sender: UIButton) {
index = 1
}
@IBAction func Button2(_ sender: UIButton) {
index = 2
}
@IBAction func Button3(_ sender: UIButton) {
index = 3
}
@IBAction func Button4(_ sender: UIButton) {
index = 4
}
func getIndex() -> Int{
return index
}
上面的代碼在 SecondViewController 中,對吧?
然后你在另一個視圖中調用下面的代碼 controller (也許是 FirstViewController)
// to get functions from SecondViewController
var second = SecondViewController()
let index = second.getIndex()
print(index)
因此,您可以在 SecondViewController 剛剛初始化之后從它中獲取索引,並且您無法在second.getIndex()
之前單擊按鈕並更改索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.