簡體   English   中英

以編程方式添加沒有故事板的容器視圖?

[英]Adding a container view programmatically without storyboard?

我在viewDidLoad有這個:

    let childViewControllerForPosts = PostsCollectionViewController(collectionViewLayout: UICollectionViewLayout())
    let cView = childViewControllerForPosts.view
    self.view.backgroundColor = UIColor.redColor()
    self.addChildViewController(childViewControllerForPosts)
    self.view.addSubview(cView)
    childViewControllerForPosts.didMoveToParentViewController(self)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(handleScroll(_:)), name: "cvScrolled", object: nil)

    cView.widthAnchor.constraintEqualToConstant(view.frame.size.width).active = true
    cView.heightAnchor.constraintEqualToConstant(view.frame.size.height).active = true
    cView.topAnchor.constraintEqualToAnchor(containerForGreyAndPurple.bottomAnchor).active = true
    cView.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true

但是,我收到一條錯誤消息,說這是非法約束,因為它沒有共同的祖先:(

這是錯誤:

...because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal.'

您沒有正確設置約束。

您首先需要使用父視圖和容器視圖添加約束,然后還需要向容器控制器添加約束。 最后,您應該在設置所有約束的末尾添加didMoveToParent。

示例如下,您可以根據自己的情況做類似的事情。

   NSLayoutConstraint.activateConstraints([
        containerView.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, constant: 10),
        containerView.trailingAnchor.constraintEqualToAnchor(view.trailingAnchor, constant: -10),
        containerView.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 10),
        containerView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor, constant: -10),
    ])


  NSLayoutConstraint.activateConstraints([
        controller.view.leadingAnchor.constraintEqualToAnchor(containerView.leadingAnchor),
        controller.view.trailingAnchor.constraintEqualToAnchor(containerView.trailingAnchor),
        controller.view.topAnchor.constraintEqualToAnchor(containerView.topAnchor),
        controller.view.bottomAnchor.constraintEqualToAnchor(containerView.bottomAnchor)
    ])


controller.didMoveToParentViewController(self)

使用自動布局來設置動態UIView以匹配容器視圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM