【问题标题】:Make subview fit inside container and resize correctly使子视图适合容器并正确调整大小
【发布时间】:2017-07-10 10:10:23
【问题描述】:

我正在尝试将动态笔尖加载为容器的子视图。我几乎让它工作了,除了子视图有一个我似乎无法摆脱的偏移量(参见下图中的粉红色视图)。

从 View Hierarchy 调试:

正如您在第二张图片中看到的那样,容器框架的位置正确,而子视图却没有,出于某种原因

我真的不知道自动布局是怎么回事。

这是处理加载 nib 并将其分配为子视图的代码:

注释掉的代码是我试图让它工作的所有东西,但没有成功。我认为自动布局可以自行工作而无需我做任何事情,但默认情况下它会加载笔尖而不调整它的大小。

这意味着前锚和顶部锚是正确的,但是笔尖会使用其全尺寸...(参见下图)

所以问题是,我需要做什么才能加载笔尖并使其适合容器视图?

【问题讨论】:

    标签: swift uiview nib


    【解决方案1】:

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

    在将 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]))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 2014-05-18
      相关资源
      最近更新 更多