Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

ios - Loading a ViewController inside a Container View

I have a containerView with full screen inside a VC. If i add a child to the containerView manually from a Storyboard doing a embed segue looks fine: enter image description here

But if I embed the VC by code:

class BannerContainerVC: UIViewController {

    @IBOutlet weak var container: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let vc = storyboard?.instantiateViewControllerWithIdentifier("test") as UIViewController
        self.container.addSubview(vc.view)
    }
}

I get super strange results:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to tell your BannerContainer view controller that it has a new child controller, and to tell the Child that it has a parent VC. This is described in the Apple Docs here. Like this:

   [self addChildViewController:vc];
   vc.view.frame = CGRectMake(0, 0, self.container.frame.size.width, self.container.frame.size.height);
   [self.container addSubview:vc.view];
   [vc didMoveToParentViewController:self];

Or in Swift:

    self.addChildViewController(vc)
    vc.view.frame = CGRectMake(0, 0, self.container.frame.size.width, self.container.frame.size.height);
    self.container.addSubview(vc.view)
    vc.didMoveToParentViewController(self)

This ensures that various layout and touch methods are passed through to the child VC; I suspect the layout problems you have may be due to those methods not currently being called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...