如何:使用 iOS 中的 StackView 视图从 XIB 自定义自定义视图

How To: Self-Sizing Custom-View from XIB with StackView View in iOS

我最近再次开始使用 Swift 进行 iOS 开发,现在正在研究自定义 UIControl。为了布局和灵活性,此自定义视图是使用 StackView 构建的。

我想达到的目标...

... 基本上只是简单地与 StackView 具有相同的功能,当我将它直接拖到情节提要中时,我通常会拥有相同的功能 - 它会调整大小以适合没问题。这与自动调整表格视图单元格基本相同。

展示

我可以将我的 CustomView 简化为一个简单的示例:它是一个包含三个标签的 StackView,Alignment 设置为 CenterDistribution Equal Centering。 StackView 将固定到左、右和顶部布局指南(或尾随、前导和顶部)。我可以使用从 XIB 加载的 CustomView 轻松地重新创建它,并将其转换为具有相同参数的 CustomView - 我将两者都附加为屏幕截图。

Screenshot of Simple StackView

Screenshot of CustomView

正在加载 XIB 文件并进行设置。

import UIKit

@IBDesignable
class CustomView: UIView {

    // loaded from NIB
    private weak var view: UIView!

    convenience init() {
        self.init(frame: CGRect())
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadNib()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.loadNib()
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        // we need to adjust the frame of the subview to no longer match the size used
        // in the XIB file BUT the actual frame we got assinged from the superview
        self.view.frame = bounds
    }

    private func loadNib ()  {
        self.view = Bundle (for: type(of: self)).loadNibNamed(
            "CustomView", owner: self, options: nil)! [0] as! UIView
        self.addSubview(self.view)
    }
}

你在这里看到的是我只是加载 XIB 文件,覆盖布局子视图以使框架适应实际视图,仅此而已。

问题

所以我的问题与通常如何处理这个问题有关。我的 StackView 中的标签有一个固有的内容大小,即,通常 StackView 只是简单地适应标签的高度而不会抱怨——如果你在情节提要中设计它。但事实并非如此,如果您将所有内容都放在 XIB 中并保持布局不变 - 如果视图以屏幕截图中的三种方式固定(顶部、前导、尾随),IB 将抱怨高度未知。

我阅读了自动布局指南并观看了 WWDC 视频 "Mysteries of AutoLayout",但这个主题对我来说仍然很新,我认为我还没有找到正确的方法。所以这是我需要帮助的地方

(1) 我应该设置约束并禁用 translatesAutoresizingMaskIntoConstraints 吗?

我首先可以而且应该做的是设置 translatesAutoresizingMaskIntoConstraints false 这样我就不会得到自动生成的约束并定义我自己的约束。所以我可以将 loadNib 更改为:

private func loadNib ()  {
    self.view = Bundle (for: type(of: self)).loadNibNamed(
        "CustomView", owner: self, options: nil)! [0] as! UIView
    self.view.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(self.view)

    self.addConstraint(NSLayoutConstraint (
        item: self
        , attribute: .bottom
        , relatedBy: .equal
        , toItem: self.view
        , attribute: .bottom
        , multiplier: 1.0
        , constant: 0))

    self.addConstraint(NSLayoutConstraint (
        item: self
        , attribute: .top
        , relatedBy: .equal
        , toItem: self.view
        , attribute: .top
        , multiplier: 1.0
        , constant: 0))

    self.addConstraint(NSLayoutConstraint (
        item: self.view
        , attribute: .leading
        , relatedBy: .equal
        , toItem: self
        , attribute: .leading
        , multiplier: 1.0
        , constant: 0))

    self.addConstraint(NSLayoutConstraint (
        item: self.view
        , attribute: .trailing
        , relatedBy: .equal
        , toItem: self
        , attribute: .trailing
        , multiplier: 1.0
        , constant: 0))
}

基本上我确实拉伸视图以适应故事板中我的 UIView 的整个宽度,并将它的顶部和底部限制在 StackView 的顶部和底部。

我在使用这个 XCode 8 时遇到了很多问题,所以我不太确定该怎么做。

(2) 或者我应该覆盖 intrinsicContentSize 吗?

我也可以通过检查所有 arrangedSubviews 的高度来简单地覆盖 intrinsicContentSize 并选择最高的那个,将我的视图高度设置为它:

override var intrinsicContentSize: CGSize {
    var size = CGSize.zero

    for (_ , aSubView) in (self.view as! UIStackView).arrangedSubviews.enumerated() {
        let subViewHeight = aSubView.intrinsicContentSize.height
        if  subViewHeight > size.height {
            size.height = aSubView.intrinsicContentSize.height
        }
    }

    // add some padding
    size.height += 0
    size.width = UIViewNoIntrinsicMetric
    return size
}

虽然这确实给了我更大的灵活性,但我还必须使固有内容大小无效,检查动态类型和许多其他我宁愿避免的东西。

(3) 我什至以 "proposed" 方式加载 XIB 吗?

或者有更好的方法,例如通过使用 UINib.instantiate?我真的找不到最佳实践方法来做到这一点。

(4) 为什么我首先要这样做?

真的,为什么?我只是将 StackView 移到了 CustomView 中。那么,为什么 StackView 现在停止自适应,为什么我必须设置顶部和底部约束?

到目前为止,帮助最大的是 中的关键短语:

"In general, auto layout is performed in a top-down fashion. In other words, a parent view layout is performed first, and then any child view layouts are performed."

..但我真的不太确定。

(5) 为什么我必须在代码中添加约束?

假设我禁用 translatesAutoresizingMaskIntoConstraints 那么我不能像 IB 中的 tableview 单元那样设置约束?它总是会转换成类似 label.top = top 的形式,因此标签将被拉伸而不是 StackView 继承 size/height。此外,我无法真正将 StackView 固定到 XIB 文件的 IB 中的容器视图。

希望有人能帮助我。干杯!

以下是对您问题的一些回答,尽管顺序不同:

(5) And why do I have to add the constraints in code?

Assuming I disable translatesAutoresizingMaskIntoConstraints then I can't set constraints like for tableview cells in IB? It'll always translate into something like label.top = top and thus the label would be stretched instead of the StackView inheriting the size/height. Also I can't really pin the StackView to it's container view in the IB for the XIB file.

您必须在代码中添加约束,在此示例中,因为您要从 nib 加载任意视图,然后将其添加到您的编码 CustomView。 nib 中的视图没有关于它将被放置到什么上下文或层次结构中的预先存在的知识,因此不可能提前定义如何将自己限制在未知的未来超级视图中。对于 Storyboard 上或原型单元格内的 StackView,该上下文及其父视图都是已知的。

对于这种情况,如果您不想手动编写约束,您可以考虑的一个不错的替代方法是 使您的 CustomView subclass UIStackView 而不是 UIView.由于 UIStackView 自动生成适当的约束,它将为您节省手动编码。请参阅下一个答案以获取一些示例代码。

(3) Am I even loading the XIB in the "proposed" way ?

Or is there a better way, e.g. by using UINib.instantiate? I really couldn't find a best-practice way to do that.

我不知道 "standard" 或 "right" 处理将 nib 加载到自定义视图中的方法。我见过各种各样的方法,都行之有效。但是,我会注意到您所做的工作比示例代码中需要的多。这是实现相同结果的更简单的方法,但也使用 UIStackView subclass 而不是 UIView subclass(如上所述):

class CustomView: UIStackView {
    required init(coder: NSCoder) {
        super.init(coder: coder)
        distribution = .fill
        alignment = .fill
        if let nibView = Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)?.first as? UIView {
            addArrangedSubview(nibView)
        }
    }
}

请注意,因为 CustomView 现在是 UIStackView 的子class,它会自动创建任何子视图所需的约束。在这种情况下,因为 distributionalignment 都设置为 .fill,它会根据需要将子视图的边缘固定到它自己的边缘。

(4) Why do I have to do this in the first place?

Really, why? I only moved the StackView into a CustomView. So why does the StackView stop adapting itself now, why do I have to set the top and bottom constraints?

实际上,这里的关键问题是您的 StackView 的 alignment 属性 of .center。也就是说,StackView 中的标签将垂直居中,但不会将它们限制在 StackView 的顶部或底部。这就像在视图内的子视图中添加 centerY 约束一样。你可以把outer view设置成你想要的任意高度,subview会居中,但是它不会"push out" outer view的顶部和底部,因为中心约束只约束中心,而不是顶部和底部边缘。

在 StackView 的情节提要版本中,StackView 之上的视图层次结构是已知的,并且还有一些选项可以根据调整掩码的大小自动生成约束。无论哪种方式,UIKit 都知道最终的 StackView 高度,并且标签将在该高度内垂直居中,但实际上不会影响它。 您需要将 StackView 的对齐方式设置为 .fill,或者添加从标签的顶部和底部到 StackView 的顶部和底部的额外约束,以便自动布局确定高度StackView应该是.

(2) Or should I override intrinsicContentSize ?

这不会有太大帮助,因为固有内容大小本身不会推出父视图的边缘,除非子视图的边缘也被限制在父视图的边缘。在任何情况下,只要您解决上述 .center 对齐问题,您就会自动获得在这种情况下所需的所有正确的固有内容大小行为。

(1) Should I set constraints and disable translatesAutoresizingMaskIntoConstraints ?

这通常是一种有效的方法。但是,如果你像我上面描述的那样子class UIStackView,你不需要做任何一个。

总结

如果你:

  1. 将您的 CustomView 创建为 UIStackView 的子class,如上面的示例代码所示

  2. 在您的故事板上创建视图设置为您的自定义 class CustomView。如果您希望 CustomView 正确地自行调整大小,则需要为其提供约束,而不是使用调整大小掩码自动生成的约束。

  3. 将您的笔尖中的 StackView 更改为将 alignment 设置为 .fill 或在至少一个标签的顶部和底部之间添加额外的约束(最有可能是大的中心那个)和堆栈视图的顶部和底部

那么自动布局应该可以正常工作,你的带有 StackView 的自定义视图应该按预期布局。