簡體   English   中英

在子視圖控制器中重用父視圖控制器故事板文件

[英]Reuse parent ViewController storyboard file in Child ViewController

使用 storyBoard 呈現 ViewController:如果 newViewController 在 StoryBoard.我們可以使用以下方法呈現它。

 let storyboard = UIStoryboard(name: "AViewController"), bundle: UIBundle.main)
let newViewcontroller = storyboard.instantiateInitialViewController() as? AViewController
  self.present(newViewcontroller, animated: false, completion: nil)

是否可以呈現一個不在故事板中但其父視圖控制器具有故事板的 ViewController

我已經以編程方式創建了一個 B 視圖控制器(沒有 StoryBoard),現在我想展示 BViewController 並且它應該使用 AViewController StoryBoard?

class AViewController : UIViewController
{
//this class is in storyboard which is generic design that I want to use it in different ways.
}
class BViewController : AViewController
{
....//
}
e.g.
 self.present(BViewController(), animated: false, completion: nil)?

當我呈現 BViewcontroller 時,它會為來自超類的參數拋出 nil。

如果您的 ViewController 確實不在故事板中,您的代碼將正常工作。 您所要做的就是在沒有nibName情況下實例化它,如下所示:

class ViewController: UIViewController {
    init() {
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }
}

普通 Storyboard ViewControllers 依賴於要創建的coder init,但是您可以使用nibName: nil初始化程序正常創建它們,只要您沒有任何插座(這是您的情況,因為 ViewController 不在故事板上)

我創建了重用故事板文件或繼承故事板文件的答案。

object_setClass (設置對象的類。)將使用 BViewController 類覆蓋 AViewController 的實例。 所以在 AViewController 之上你可以添加更多的方法。

當你有類似的視圖控制器時,改動很小。 您必須創建不同的視圖控制器。 使用此方法,您可以在帶有情節提要的基本視圖控制器上創建並重用該視圖控制器。

 class BViewController{
       static func vcInstanceFromStoryboard() ->BViewController? {
            let storyboard = UIStoryboard(name: "AViewController"), bundle: UIBundle.main)
            let instance = storyboard.instantiateInitialViewController() as? AViewController
            object_setClass(instance, BViewController.self) // 
            return (instance as? BViewController)!
        }
    .....
    } 

This is an example of how do we use it:
let vc = BViewController.vcInstanceFromStoryboard()
self.present(vc , animation : true)

一切皆有可能以編程方式實現。 通過 Interface Builder 並非一切皆有可能。 故事板只是 Interface Builder 的一個組件。

從根以編程方式呈現視圖控制器:

@objc private func presentViewController() {

    guard let root = UIApplication.shared.keyWindow!.rootViewController else {
        return
    }

    let destination = SomeViewController()
    destination.transitioningDelegate = YourAnimationVendor()
    destination.modalPresentationStyle = .custom
    root.present(destination, animated: true, completion: nil)

}

您可以省略過渡委托(和自定義動畫供應商)並使用庫存 UIKit 動畫呈現,例如.fullScreen而不是.custom

@objc private func presentViewController() {

    guard let root = UIApplication.shared.keyWindow!.rootViewController else {
        return
    }

    let destination = SomeViewController()
    destination.modalPresentationStyle = .fullScreen
    root.present(destination, animated: true, completion: nil)

}

暫無
暫無

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

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