以编程方式转到下一个视图控制器

Lim*_*ico 5 function iboutlet ibaction swift

我想知道如何创建一个功能,可以在我点击登录按钮后,使用代码/编程方式移动到登录页面

override func viewDidLoad() {
    super.viewDidLoad()


    //make the login button
    let loginButton = UIButton(frame: CGRectMake(20, 640, 175, 75))
    loginButton.setTitle("Login", forState: UIControlState.Normal)
    loginButton.addTarget(self, action: #selector(ViewController.tapActionButton), forControlEvents: UIControlEvents.TouchUpInside)
    loginButton.backgroundColor = UIColor.init(red: 255, green: 215, blue: 0, alpha: 0.8)
    loginButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    loginButton.titleLabel!.font = UIFont(name: "StarJediSpecialEdition", size: 30)
    self.view.addSubview(loginButton)

    //make the register button
    let registerButton = UIButton(frame: CGRectMake(220,640,175,75))
    registerButton.setTitle("Register", forState: UIControlState.Normal)
    registerButton.addTarget(self, action: #selector(ViewController.tapActionButton), forControlEvents: UIControlEvents.TouchUpInside)
    registerButton.backgroundColor = UIColor.init(red: 255, green: 215, blue: 0, alpha: 0.8)
    registerButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
    registerButton.titleLabel!.font = UIFont(name: "StarJedi Special Edition", size: 30)
    self.view.addSubview(registerButton)}        func tapActionButton(sender:UIButton!){
    print("Button is working")
}
Run Code Online (Sandbox Code Playgroud)

所以我的功能现在是这样,但我实际上需要点击按钮移动到下一个视图控制器,任何人都请帮助我

Aks*_*Aks 13

根据您创建ViewController的方式,有多种方法可以执行此操作.

  1. 故事板和Segue(对于大多数情况,这非常好)

    在您的登录视图控制器和您想要显示的ViewController之间创建segue(例如: - ABCViewController),为您的segue提供标识符和演示文稿样式.对于你的情况,它将是Show 例

现在在LoginViewController中覆盖下面的方法

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
   if segue.identifier == "YourSegueIdentifier"
       let abcViewController = segue.destinationViewController as! ABCViewController
       abcViewController.title = "Home"
   }
}
Run Code Online (Sandbox Code Playgroud)

在loginButton操作上:

performSegueWithIdentifier("YourSegueIdentifier", sender: nil)
Run Code Online (Sandbox Code Playgroud)

你完成了.

  1. 从故事板创建后以编程方式推送视图控制器

为此,你必须给你的视图控制器在故事板的标识符,然后你可以使用它实例化和使用推:

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let abcViewController = storyboard.instantiateViewControllerWithIdentifier("ABCViewControlleridentifier") as! ABCViewController
abcViewController.title = "ABC"
navigationController?.pushViewController(abcViewController, animated: true)
Run Code Online (Sandbox Code Playgroud)


Dav*_*ark 5

您需要创建下一个视图控制器的实例,然后呈现或推送该视图控制器

模态呈现:

self.presentViewController(nextVC, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

或推:

self.navigationController?.pushViewController(nextVC, animated: true)
Run Code Online (Sandbox Code Playgroud)

所有与 segue 相关的东西都适用于故事板

干杯!