【问题标题】:Can you change view controllers without segue?你可以在没有 segue 的情况下更改视图控制器吗?
【发布时间】:2020-02-21 10:08:33
【问题描述】:

基本上我有一个改变标题的按钮,如果按钮标题是什么我希望按钮将用户带到不同的地方,如果按钮标题是别的东西

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

}

【问题讨论】:

    标签: swift user-interface uiviewcontroller segue


    【解决方案1】:

    根据 if 检查实例化 ViewController,并呈现它:

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

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

    【讨论】:

      【解决方案2】:

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

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

      您只需在buttonName'stitle 上放置一个switch-case 并显示相关的控制器act1act2。使用storyboard 创建act1act2

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

      }

      不要忘记将Act1ViewControllerAct2ViewController 设置为storyboard 中各自控制器的storyboardID

      【讨论】:

      • 我认为我的 let act1 = act1ViewController() let act2 = act2ViewController() 是我尝试运行您的代码时的问题...我该如何解决??
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 2011-09-11
      相关资源
      最近更新 更多