iOS:添加 subview Controller 不显示子组件

标签 ios swift

有两个 View Controller ,MainViewControllerChildViewController,我想将 ChildViewController 添加到 MainViewController 和这个是我的代码:

MainViewController.swift

class MainViewController: UIViewController {
    
    @IBOutlet weak var containerView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.add(ChildViewController(), in: containerView)
    }

}

ChildViewController.swift

class ChildViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        print("ChildViewController is loaded")
    }

}

UIViewController+Ext.swift

extension UIViewController {
    func add(_ child: UIViewController, in container: UIView) {
        addChild(child)
        container.addSubview(child.view)
        child.view.frame = container.bounds
        child.didMove(toParent: self)
    }
    
    func add(_ child: UIViewController) {
        add(child, in: view)
    }
    
    func remove(from view: UIView) {
        guard parent != nil else {
            return
        }
        
        willMove(toParent: nil)
        removeFromParent()
        view.removeFromSuperview()
    }
    
    func remove() {
        remove(from: view)
    }
}

Storyboard enter image description here

输出: enter image description here

ChildViewController is loaded”出现在终端中,但未加载 UI 组件。

最佳答案

self.add(ChildViewController(), in: containerView)

您正在以编程方式创建一个 ChildViewController 实例,而不是从 Storyboard 中获取它。

if let childViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") {
    self.add(ChildViewController(), in: containerView)
}

关于iOS:添加 subview Controller 不显示子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414495/

相关文章:

ios - 适用于 iOS 的 Google map ,swift - 如何在标记之间显示整条多段线?

objective-c - 防止 ARC 取消分配当前未使用但很快就会使用的东西?

ios - Ionic 4 Ios构建越来越黑屏

iphone - 数组,大小不是期望值

ios - 使用 NSUserDefaults 保存 ViewController 页面上的触摸按钮,该按钮与导航 Controller 相关

ios - 在 Swift 中,如何让其他应用在我的应用打开时继续播放音频?

javascript - 尝试将旧的 React native 文件更新为 0.30

ios - 使用正交滚动行为的水平 uicollectionview 中的大差距

ios - 实例成员 'playerID' 不能用于类型 'GKPlayer'

xcode - 如何在联系人体内使用 node.name?