0
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.

addChildでUIViewControllerに親子関係を持たせる

Posted at

addChild(childController: UIViewController)を使うとUIViewControllerの階下にUIViewControllerを持たせることができます。UI部品を配置するためのaddSubView()と違いaddChild()はUIViewControllerそのものを重ねることができます。

スクリーンショット 2021-01-29 14.01.45.jpg

ソースコード

親となるViewControllerではaddChild()だけでなくaddSubview()も呼ばないと階層関係になっていることを確認できなかった。

ParentViewController
class ParentViewController: UIViewController {
    
    override func viewDidLoad() {
        let childVC = ChildViewController()
        super.viewDidLoad()
        view.backgroundColor = .red
        view.addSubview(childVC.view)
        addChild(childVC)
        childVC.didMove(toParent: self)
    }
}
class ChildViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .blue
    }
}
0
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
0
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?