Swift 你能在没有segue的情况下更改视图控制器吗?
基本上我有一个改变标题的按钮,如果按钮标题是我想让按钮带用户去不同的地方,如果按钮标题是其他东西Swift 你能在没有segue的情况下更改视图控制器吗?,swift,user-interface,uiviewcontroller,segue,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 se
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)
}
}根据if检查实例化ViewController,并显示它:
let storyBoard: UIStoryboard = UIStoryboard(name: "MyStoryboard", bundle: nil)
let destinationVC = storyBoard.instantiateViewController(withIdentifier: "ViewControllerIdentifier") as! NewViewController
present(destinationVC, animated: true, completion: nil)
如果要显示的两个控制器是
class Act1ViewController: UIViewController {
//your code...
}
class Act2ViewController: UIViewController {
//your code...
}
您只需在按钮名称上放置开关盒,并显示相关控制器act1
或act2
。使用故事板创建act1
和act2
@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
和Act2ViewController
设置为storyboard
中相应控制器的storyboard
我认为我的let act1=Act1ViewController()let act2=Act2ViewController()是我尝试运行代码时的问题。。。我怎么修理它??
@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
}
}