【问题标题】:Change view controller using action button使用操作按钮更改视图控制器
【发布时间】:2014-10-24 04:04:59
【问题描述】:

如何使用 UIButton 切换视图控制器?这是我的代码:

@IBAction func scanAction(sender: AnyObject) {
      //switch view controller 
}

当我单击“扫描”按钮时,它将转到登录表单。

我在Main.storyboard中的视图控制器是这样的

我该如何继续?

【问题讨论】:

    标签: ios swift xcode6


    【解决方案1】:

    我已经找到答案了

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
    
    let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
    self.presentViewController(nextViewController, animated:true, completion:nil)
    

    【讨论】:

      【解决方案2】:

      一种方法是从按钮中获得模态序列。不需要 IBOutlet。

      以编程方式:

      @IBAction func scanButton (sender: UIButton!) {
      
          performSegueWithIdentifier("nextView", sender: self)
      
      }
      

      您应该添加模态序列并命名标识符。您将 VC1 连接到 VC2。

      【讨论】:

      • 我想以编程方式进行
      • 我为 VC 添加了编程指令。除非您使用导航控制器,否则 Mini 的示例将不起作用。
      • 为什么我得到这个错误,/Users/MNurdin/Documents/iOS/UpassMobile/UpassMobile/ViewController.swift:32:13:在闭包中隐式使用'self';使用“自我”。使捕获语义明确
      • 将你的项目发布到github,我会修复它。
      【解决方案3】:

      最简单的方法是创建一个 UINavigationViewController。然后在当前屏幕上添加一个 Button。 现在按下控制并将按钮拖动到目标视图控制器。就是这样。

      来源:iOs UINavigationViewController

      【讨论】:

        【解决方案4】:

        实际上有一个没有硬编码代码的答案。 在您的故事板中,您可以控制将按钮拖动到下一个视图控制器并在那里定义segue。这将确保每当您按下按钮时,segue 都会触发。您可以在触发的 segues 处的按钮“连接检查器”中看到这一点。

        如果您想在目标视图控制器中放入数据,您可以在按钮上添加一个不作为并将数据放入为 segue 功能做准备。很酷的一点是,您触发的 segues 仍然会从您的按钮触发。这部分看起来像这样:

            @IBAction func buttonPressed(_ sender: UIButton) {
                someImportantData = "some data if needed"
                //no need to trigger segue :)
            }
        
            //not your case, but in order to understand the sage of this approach
            @IBAction func button2Pressed(_ sender: UIButton) {
                someImportantData = "some data2 if needed"
                //no need to trigger segue :)
            }
        
            override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                //retrieve the destination view controller for free
                if let myDestincationViewController = (segue.destination as? MyDestincationViewController) {
                    myDestincationViewController.someImportantData = someImportantData
                }
            }
        

        这样,您不需要任何硬编码字符串用于 segue 标识符、情节提要标识符等,如果需要,您甚至可以准备目标视图控制器。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-11
          • 1970-01-01
          • 2016-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-09
          相关资源
          最近更新 更多