当不同的按钮指向同一个ViewController时,我如何在swift中知道哪个按钮被按下了?

问题描述 投票:0回答:1

我有四个按钮,都指向同一个视图控制器,我需要知道哪个按钮被按下了,因为每个按钮的设置略有不同。我需要知道哪个按钮被按下了,因为每个按钮的视图控制器设置略有不同。我尝试了以下内容: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
    }

之后将打开的视图控制器

// to get functions from SecondViewController
var second = SecondViewController()

let index = second.getIndex()
print(index)

不幸的是,它总是打印0。我想是因为我一开始就把索引设置为0,但我不明白为什么当按钮被按下时,数值不更新。

我能做什么?

ios swift uibutton getvalue
1个回答
1
投票

第二个视图控制器(前一个包含按钮的视图控制器)

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)
}

2
投票

我猜你使用的是segue,所以你的segue是在你的IBAction更新你的索引值之前执行的。有一个类似的问题& 解决方案 此处

因此,为了解决这个问题,给你的转场符一个标识符,然后调用 performSegueWithIdentifier 在你的IBAction方法中,如果我没有理解错的话,你肯定会得到index为0。


-2
投票

如果我的理解正确的话,你一定会得到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中,对吗?

然后在另一个视图控制器中调用下面的代码(可能是FirstViewController)。

// to get functions from SecondViewController
var second = SecondViewController()

let index = second.getIndex()
print(index)

所以你在SecondViewController刚刚被初始化后就得到了索引,你没有办法在点击按钮之前改变索引。second.getIndex().

© www.soinside.com 2019 - 2024. All rights reserved.