如何以编程方式呈现 ViewController?

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

我目前有一个 EventPage class 声明为 UIViewController 类型,但是在按下带有填充文本字段的保存按钮后,会发生到空白 ViewController 的转换。我已将 class 附加到 main.storyboard 中正确的 ViewController。

这里的问题是您正在创建一个新的 EventPage 但它不继承 Storyboard。

1

转到故事板中的检查器,select 你的视图控制器,并为你的视图控制器写一个标识符(可以是任何东西)

写在故事板ID:

2

替换

present(EventPage(), animated:true)

有 (不要忘记将 'MYIDENTIFIER' 替换为您之前输入的 ID)

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)

备注

如果你的 Storyboard 文件名不叫 Main,请将步骤 2 中的“Main”替换为你的 Storyboard 文件名(不包括 .storyboard)