3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUIのUIHostingControllerではviewDidLoadは呼ばれない

Last updated at Posted at 2020-09-01

まとめ

UIHostingControllerではviewDidLoadは呼ばれないので注意しましょう。

解説

class CustomViewHostingViewController: UIHostingController<CustomView> {
    
    required init?(coder: NSCoder) {
        fatalError()
    }
    
    override init(rootView: CustomView) {
        super.init(rootView: rootView)
    }
    
    convenience init() {
        let customView = CustomView()
        self.init(rootView: customView)
        self.view.backgroundColor = .clear
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        print("*** didLoad: \(view.backgroundColor)")
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        print("*** willLayout: \(view.backgroundColor)")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        print("*** didLayout: \(view.backgroundColor)")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("*** willAppear: \(view.backgroundColor)")
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        print("*** didappear: \(view.backgroundColor)")
    }

}

コンソールログは以下の通り

*** willAppear: Optional(UIExtendedGrayColorSpace 0 0)
*** willLayout: Optional(UIExtendedGrayColorSpace 0 0)
*** didLayout: Optional(UIExtendedGrayColorSpace 0 0)
*** willLayout: Optional(UIExtendedGrayColorSpace 0 0)
*** didLayout: Optional(UIExtendedGrayColorSpace 0 0)
*** didappear: Optional(UIExtendedGrayColorSpace 0 0)

ドキュメント
https://developer.apple.com/documentation/swiftui/uihostingcontroller

ドキュメントには

Use the hosting controller like you would any other view controller, by presenting it or embedding it as a child view controller in your interface.

って書いてあるから、当然 viewDidLoad も呼ばれるものかと思いきや、呼ばれず、viewDidLoad に初期値をセットしても反映されないのでした。

initで初期値を設定して無事透明な背景色を表示しました。

サンプルプロジェクト -> https://github.com/justin999/SwiftUIInVC

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?