简体   繁体   中英

How do I present ViewController programatically?

import UIKit

//EventList ViewController
class EventPage: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
}

class EventForm: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        }
    
    //IBOutlets
    @IBOutlet weak var eventNameField: UITextField!
    @IBOutlet weak var fromTimePicker: UIDatePicker!
    @IBOutlet weak var toTimePicker: UIDatePicker!
    @IBOutlet weak var colorPreview: UIView!

    @IBAction func cancel(_ sender: Any) {
        
        //empty text field
        eventNameField.text = ""
    }
    
    @IBAction func save(_ sender: Any) {
        if (eventNameField.hasText) {
            
            //fix error handling
            eventNameField.backgroundColor = UIColor.systemGray2
            
            //pull data from fields
            let text = eventNameField.text!
            let fromTime = fromTimePicker.date
            let toTime = toTimePicker.date
        
            //initialize object
            let currentEvent = EventModel(eventName: text, fromTime: fromTime, toTime: toTime, color: storedColor)
        
            //append to data model
            EventDataArray.append(currentEvent)
            
            //transition
            present(EventPage(), animated:true)
            
        }
        else {
            eventNameField.backgroundColor = UIColor.systemRed
        }
    }
}

I currently have an EventPage class declared as type UIViewController, but upon pressing the save button with a populated text field a transition to a blank ViewController occurs. I've attached the class to the correct ViewController in main.storyboard.

The problem in here is that you are creating a new EventPage but it doesn't inherit from Storyboard.

1

Go to the inspector in your storyboard, select your View Controller, and write an identifier for your View Controller (can be anything)

Write it in Storyboard ID :

图片

2

Replace

present(EventPage(), animated:true)

With (don't forget to replace 'MYIDENTIFIER' with the id you entered earlier)

let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MYIDENTIFIER") as! EventPage
// If you need to do any configurations to your view controller, do that in here.
// For example:
// viewController.label.text = "Hello, world!"
present(viewController, animated:true)

Note

If the name of your Storyboard file name is not called Main , replace "Main" in step 2 with the name of your storyboard file (excluding.storyboard)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM