【问题标题】:How do I know in swift which button was pressed when different buttons lead to the same ViewController?当不同的按钮通向同一个 ViewController 时,我如何快速知道按下了哪个按钮?
【发布时间】:2020-09-24 09:06:42
【问题描述】:

我有四个按钮,它们都通向同一个视图控制器。我需要知道按下了哪个按钮,因为每个按钮的视图控制器设置略有不同。 我尝试了以下方法: 按下其中一个按钮的 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,但我不明白为什么按下按钮时值不更新。

我能做什么?

【问题讨论】:

标签: ios swift uibutton getvalue


【解决方案1】:

我猜你正在使用 segue,所以你的 segue 在你的 IBAction 可以更新你的索引值之前执行。有类似的问题&解决方法here

因此,要解决此问题,请为您的 segue 提供一个标识符,并从您的 IBAction 方法中调用 performSegueWithIdentifier

【讨论】:

  • 我不认识任何一个兄弟....我不知道为什么人们在不评论原因的情况下投反对票
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果我理解正确,你肯定会得到 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() 之前单击按钮并更改索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2021-10-08
      相关资源
      最近更新 更多