【发布时间】:2017-05-31 09:52:50
【问题描述】:
我有以下 UIView:
它是一个包含三个子视图的 UIView。一个常规的 UILabel (Hello World) 在顶部,一个自定义的 UIViewController (CategoryList) 包含一个带有按钮 (alpha,beta, ...) 的 CollectionView 和另一个只有一个标签 (SALUT) 的自定义 UIViewController。
我以编程方式进行自动布局,并将 SALUT (var sCtrl) 放置在 CategoryList (var catList) 下方
sCtrl.view.topAnchor.constraint(equalTo: catList.view.bottomAnchor).isActive = true
这会导致上图,其中 SALUT 没有像我希望的那样位于类别列表下方。我有点理解为什么当我设置约束时,按钮尚未在 CollectionView 中正确布局,因此未设置 catList 的底部锚点。
在 CategoryList:UIVIewController 中,为了让集合视图获得正确的高度,我有以下内容。
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
heightConstraint = collectionView.heightAnchor.constraint(equalToConstant: collectionView.collectionViewLayout.collectionViewContentSize.height)
self.view.addConstraint(heightConstraint)
}
这可行,但由于在 SALUT 上设置约束后调用 viewDidLayoutSubviews(),所以 SALUT 位置是错误的。我怎样才能以一种简单的方式把它做好? (我想我可以为我的主视图制作一个控制器,并在布局子视图时检查那里,然后更新子视图的位置,但这对我来说似乎过于复杂)。
主视图的完整代码如下,您可以看到布局定位代码。如果需要,我也可以提供子视图代码,但我认为不需要它,因为它们应该被视为黑盒子......
class MyView: UIView {
let label = UILabel()
var sCtrl : SubController
var catList : CategoryList
var topConstraint = NSLayoutConstraint()
override init(frame: CGRect) {
sCtrl = SubController()
catList = CategoryList()
super.init(frame: frame)
setup()
}
private func setup() {
self.backgroundColor = UIColor.green
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.yellow
label.text = "Hello world"
label.textAlignment = .center
self.addSubview(label)
catList.view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(catList.view)
sCtrl.view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(sCtrl.view)
let margins = self.layoutMarginsGuide
label.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 0).isActive = true
label.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 0).isActive = true
label.topAnchor.constraint(equalTo: margins.topAnchor, constant: 0).isActive = true
label.heightAnchor.constraint(equalToConstant: 100.0).isActive=true
catList.view.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 0).isActive = true
catList.view.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 1.0).isActive = true
catList.view.widthAnchor.constraint(equalTo: margins.widthAnchor, multiplier: 1.0).isActive = true
catList.view.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant:0).isActive = true
sCtrl.view.topAnchor.constraint(equalTo: catList.view.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let v = MyView(frame: CGRect(x: 0, y: 0, width: 400, height: 600))
【问题讨论】:
-
你可以检查你的
CategoryList类是否有内在的内容大小?
标签: ios swift uiview autolayout