如何使用 Swift 在 iOS 8 中正确添加子视图控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26599858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:23:36  来源:igfitidea点击:

How To Properly Add Child View Controller in iOS 8 With Swift

iosswiftuiviewcontrollerstoryboarduicollectionview

提问by Aggressor

I've been going through the documentation and still seem to be on a sticking point.

我一直在浏览文档,但似乎仍然在症结上。

I have a view controller object C_SelectPhoto. This has a container view. Inside the container view I want the childed view controller, C_SelectPhotoControllerView, to fit inside it. It will just be an array of photos. However, setting the frame and adding the child view controller is not working. If I move the x value of the desired child view controller, no effect happens.

我有一个视图控制器对象 C_SelectPhoto。这有一个容器视图。在容器视图中,我希望将子视图控制器 C_SelectPhotoControllerView 放入其中。这将只是一组照片。但是,设置框架和添加子视图控制器不起作用。如果我移动所需子视图控制器的 x 值,则不会发生任何效果。

To figure out what is going on I color coded everything. The container, below, is orange. The view the container expects, according to the storyboard is yellow. The view I actually want to fit in there is red.

为了弄清楚发生了什么,我对所有内容进行了颜色编码。下面的容器是橙色的。根据情节提要,容器期望的视图是黄色的。我实际上想要适应的视图是红色的。

Here is the storyboard:

这是故事板:

enter image description here

在此处输入图片说明

Here is my controller code for C_SelectPhoto

这是我的 C_SelectPhoto 控制器代码

class C_SelectPhoto:Controller
{
    @IBOutlet weak var selectPhotoControllerView: UIView!
    var _collectionViewController:C_SelectPhotoControllerView!

    //TODO PERMISSION IS NEEDED BEFORE FETCHING
    func initController()
    {   
        _collectionViewController = Controller.STORYBOARD.instantiateViewControllerWithIdentifier("selectPhotoControllerView") as C_SelectPhotoControllerView
        displayControllerViewController()
    }

    //show the photo selection
    private func displayControllerViewController()
    {
        addChildViewController(_collectionViewController)
        _collectionViewController.view.frame = CGRectMake(100, 0, 500, 500)
        self.view.addSubview(_collectionViewController.view)
        _collectionViewController.didMoveToParentViewController(self)
    }
}

However the result is produces is below: enter image description here

然而结果是产生如下: 在此处输入图片说明

First, the yellow class shouldn't be added at all, I wanted only the red (the UICollectionViewController class). Second, I can tell the red class is being added to the wrong spot because its x value hasn't moved it over at all.

首先,根本不应该添加黄色类,我只想要红色(UICollectionViewController 类)。其次,我可以看出 red 类被添加到了错误的位置,因为它的 x 值根本没有移动它。

So my question is: How can I add a UIContainerViewController, as a child to the main view controller, C_SelectPhoto, but have the UIContainerViewController frame FIT the container I have in the main view controller?

所以我的问题是:如何将 UIContainerViewController 作为子项添加到主视图控制器 C_SelectPhoto,但让 UIContainerViewController 框架适合我在主视图控制器中的容器?

Thank you!!!

谢谢!!!

NOTE: The views I am trying to add are UICollectionViewControllers. When I add a UIViewController, the framing works just fine, but as you can see when adding the UICollectionViewControllers, the framing does NOT work, and they are getting added to random offsets and are not respecting my attempts to size them with frame assignments.

注意:我尝试添加的视图是 UICollectionViewControllers。当我添加 UIViewController 时,框架工作得很好,但是正如您在添加 UICollectionViewControllers 时所看到的那样,框架不起作用,并且它们被添加到随机偏移中并且不尊重我尝试使用框架分配调整它们的大小。

采纳答案by rdelmar

If you want the red controller to be the child controller, delete the yellow one, and control-drag from the container to the red controller. There's no need to add it in code, or do any resizing. The red controller will be set to the same size as the container in the storyboard.

如果您希望红色控制器成为子控制器,请删除黄色控制器,然后从容器中按住 Control 拖动到红色控制器。无需在代码中添加它,也无需调整大小。红色控制器将设置为与故事板中的容器相同的大小。

回答by Phani Sai

use following Extension for adding childViewController On View

使用以下扩展在视图上添加 childViewController

extension UIViewController {   
func configureChildViewController(childController: UIViewController, onView: UIView?) {
    var holderView = self.view
    if let onView = onView {
        holderView = onView
    }
    addChildViewController(childController)
    holderView.addSubview(childController.view)
    constrainViewEqual(holderView, view: childController.view)
    childController.didMoveToParentViewController(self)
    childController.willMoveToParentViewController(self)
}


func constrainViewEqual(holderView: UIView, view: UIView) {
    view.translatesAutoresizingMaskIntoConstraints = false
    //pin 100 points from the top of the super
    let pinTop = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal,
        toItem: holderView, attribute: .Top, multiplier: 1.0, constant: 0)
    let pinBottom = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal,
        toItem: holderView, attribute: .Bottom, multiplier: 1.0, constant: 0)
    let pinLeft = NSLayoutConstraint(item: view, attribute: .Left, relatedBy: .Equal,
        toItem: holderView, attribute: .Left, multiplier: 1.0, constant: 0)
    let pinRight = NSLayoutConstraint(item: view, attribute: .Right, relatedBy: .Equal,
        toItem: holderView, attribute: .Right, multiplier: 1.0, constant: 0)

    holderView.addConstraints([pinTop, pinBottom, pinLeft, pinRight])
}}

回答by Bhuvan Bhatt

Updated for Swift 5+

为 Swift 5+ 更新

Just one line in your view controller to add child view controller.

只需在视图控制器中添加一行即可添加子视图控制器。

Super scalable methods in the extension if you want to add it on any custom view.

如果您想将其添加到任何自定义视图中,则扩展中的超级可扩展方法。

 public extension UIViewController {

    /// Adds child view controller to the parent.
    ///
    /// - Parameter child: Child view controller.
    func add(_ child: UIViewController) {
        addChild(child)
        view.addSubview(child.view)
        child.didMove(toParent: self)
    }

    /// It removes the child view controller from the parent.
    func remove() {
        guard parent != nil else {
            return
        }
        willMove(toParent: nil)
        removeFromParent()
        view.removeFromSuperview()
    }
}

How to use:

如何使用:

Adding:In the view controller where you want to add the child view controller.

添加:在要添加子视图控制器的视图控制器中。

// let yourChildViewController = Load fro the storyboard or XIB
add(yourChildViewController)

Removing:

删除:

yourChildViewController.remove()