Programmatically navigate to another view controller/scene

后端 未结 19 3305
一向
一向 2020-11-27 11:29

I got an error message during navigating from first view controller to second view controller. My coding is like this one

let vc = LoginViewController(nibNam         


        
19条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 12:04

    If you are building UI without drag and drop (without using storyboard) and want to navigate default page or ViewController.swift to another page? Follow these steps 1) add a class (.swift) 2) Import UIKit 3) Declare class name like

    class DemoNavigationClass :UIViewController{
         override func viewDidLoad(){
             let lbl_Hello = UILabel(frame: CGRect(x:self.view.frame.width/3, y:self.view.frame.height/2, 200, 30));
    lbl_Hello.text = "You are on Next Page"
    lbl_Hello.textColor = UIColor.white
    self.view.addSubview(lbl_Hello)
        }
    }
    

    after creating second page come back to first page (ViewController.swift) Here make a button in viewDidLoad method

    let button = UIButton()
    button.frame = (frame: CGRect(x: self.view.frame.width/3, y: self.view.frame.height/1.5,   width: 200, height: 50))
     button.backgroundColor = UIColor.red
     button.setTitle("Go to Next ", for: .normal)
     button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
     self.view.addSubview(button)
    

    now define buttonAction method outside of viewDidLoad() in same class

    func buttonAction(sender: UIButton!) 
    {
        let obj : DemoNavigationClass = DemoNavigationClass();
        self.navigationController?.pushViewController(obj, animated: true)
    }
    

    Keep one thing that i forget in main.storyboard there is a scene with a arrow, select that arrow and press delete button

    now drag and drop a navigationcontroller and delete tableview which comes with navaigation controller. select navigationcontroller press control on keyboard and drag it in to another scene on storyboard that is ViewController. This mean that your viewcontroller become root viewcontroller hope this help you Thanks in main.storyboard , drag and drop navigationcontroller,

提交回复
热议问题