让子视图适应容器并正确调整大小

5

我正在尝试将动态nib作为容器的子视图加载。我已经接近成功,但是子视图有一个偏移量,我似乎无法去除它(参见下面图片中的粉色视图)。

enter image description here

从视图层次结构调试:

enter image description here

正如您在第二张图片中所看到的那样,容器框架正确地定位了,而子视图则没有,由于某种原因。
我不太清楚自动布局发生了什么。
以下是处理加载nib并将其分配为子视图的代码:

enter image description here

注释掉的代码是我尝试过但没有成功的所有方法。我以为自动布局会自己工作而无需我做任何事情,但默认情况下它会加载nib文件而不调整其大小。
这意味着前导和顶部锚点是正确的,但是nib文件然后使用其完整大小...(参见下面的图片)

enter image description here

所以问题是,我需要做什么才能加载nib并使其适合容器视图?
1个回答

4

您应该给NibView添加约束,而不是设置其边界和框架。

在将NibView添加为内容视图的子视图后,请尝试调用以下函数(addFullScreenConstraint):

  extension UIView {

    /// Adds constraints to this `UIView` instances `superview` object
    /// to make sure this always has the same size as the superview.
    /// Please note that this has no effect if its `superview` is `nil`
    /// – add this `UIView` instance as a subview before calling this.
    func addFullScreenConstraints() {
        guard let superview = self.superview else {
            return
        }

        self.translatesAutoresizingMaskIntoConstraints = false
        superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|",
                                                                options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
        superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|",
                                                                options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接