您可以不加更改地更改视图控制器吗?

时间:2020-02-21 10:08:33

标签: swift user-interface uiviewcontroller segue

基本上我有一个可以更改标题的按钮,如果按钮标题是某种东西,我希望该按钮将用户带到与按钮标题是其他东西不同的地方

let act1 = act1ViewController()
let act2 = act2ViewController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.buttonName.setTitle(self.text, for: .normal)
    // Do any additional setup after loading the view.
}

@IBAction func buttonPressed(_ sender: UIButton) {

   if text == "cheer up" {
    self.present(act1, animated: true, completion: nil)

}
   else if text == "yay" {
    self.present(act2, animated: true, completion: nil)
    }

}

2 个答案:

答案 0 :(得分:0)

根据if检查实例化ViewController并显示它:

let storyBoard: UIStoryboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
let destinationVC = storyBoard.instantiateViewController(withIdentifier: "ViewControllerIdentifier") as! NewViewController
present(destinationVC, animated: true, completion: nil)

仅记得在情节提要中设置标识符

答案 1 :(得分:0)

如果要显示的2个控制器是

class Act1ViewController: UIViewController {
    //your code...
}

class Act2ViewController: UIViewController {
    //your code...
}

您只需要在buttonName's title上放一个开关盒,然后出示相关的控制器act1act2。使用act1创建act2storyboard

@IBAction func buttonPressed(_ sender: UIButton) {
    switch sender.titleLabel?.text {
    case "cheer up":
        if let act1 = self.storyboard?.instantiateViewController(withIdentifier: "Act1ViewController") as? Act1ViewController {
            self.present(act1, animated: true, completion: nil)
        }

    case "yay":
        if let act2 = self.storyboard?.instantiateViewController(withIdentifier: "Act2ViewController") as? Act2ViewController {
            self.present(act2, animated: true, completion: nil)
        }

    default:
        break
    }
}

}

请不要忘记将Act1ViewController中的Act2ViewControllerstoryboardID设置为storyboard中各个控制器的{{1}}。