簡體   English   中英

不使用故事板時使用 Swift 初始化 UIViewController 的正確方法是什么?

[英]What is the proper way to initialize a UIViewController using Swift when not using Storyboards?

我想擺脫項目中的故事板。 一切都是用代碼編寫的,但我仍然有 UIViewController(s) 作為參考。

當嘗試顯示 UIViewController 時,我通常使用下面顯示的方法,並且我能夠訪問該特定 UIViewController 的變量。

func presentAttributeOptions(_ attribute: Attribute, controller: ProductViewController) {

    let storyboard = UIStoryboard(name: Storyboards.Product, bundle: nil)
    let destination = storyboard.instantiateViewController(withIdentifier: Controllers.Attributes) as! AttributeOptionsViewController

    destination.providesPresentationContextTransitionStyle = true
    destination.definesPresentationContext = true
    destination.modalPresentationStyle = .overFullScreen
    destination.attribute = attribute
    destination.selectOptionDelegate = controller
    present(destination, animated: true, completion: nil)
}

但是,刪除對 Storyboard 的引用並使用下面顯示的方法,我收到錯誤,例如“'ProductViewController' 類型的值沒有成員'屬性'”和“'ProductViewController' 類型的值沒有成員'selectOptionDelegate” '"

func presentAttributeOptions(_ attribute: Attribute, controller: ProductViewController) {

    let destination = ProductViewController()

    destination.providesPresentationContextTransitionStyle = true
    destination.definesPresentationContext = true
    destination.modalPresentationStyle = .overFullScreen
    destination.attribute = attribute
    destination.selectOptionDelegate = controller
    present(destination, animated: true, completion: nil)
}

我找到了幾個答案,但似乎沒有一個有效,例如將下面顯示的以下 init() 方法添加到 UIViewController。我錯過了什么?

// This allows you to initialize your custom UIViewController without a nib or bundle.
convenience init() {
    self.init(nibName: nil, bundle: nil)
}

// This extends the superclass.
override init(nibName: String?, bundle: Bundle?) {
    super.init(nibName: nil, bundle: nil)
}

// This is also necessary when extending the superclass.
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented") // or see Roman Sausarnes's answer
}

我只看到這個:

  • storyboard,目標是 AttributeOptionsViewController 類型
  • 沒有,目標是 ProductionViewController 類型

這可能是一個原因

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM