【发布时间】:2020-04-22 07:18:36
【问题描述】:
我正在尝试创建一个 ViewBuilder 类来设置视图并将它们返回给调用者。然后,调用者只需约束一个视图,该视图包含一些在视图内受约束的子视图。这样,我想保存一些代码。
代码会变得更清楚:
我的 Collection-View-Cell 中的代码:
let postView = ViewComponentsBuilder.generatePostView(postItem: contentInteraction!.nativeContent as! Post)
postView.layer.borderWidth = 1
self.contentView.addSubview(postView)
postView.anchor(top: profileImageView.bottomAnchor, left: self.contentView.leftAnchor, bottom: nil, right: self.contentView.rightAnchor, paddingTop: 0, paddingLeft: 16, paddingBottom: 0, paddingRight: 16, width: 0, height: 0)
postView.layoutSubviews()
postView.sizeToFit()
print(postView.frame.height) // always prints 0
ViewBuilder 类中的代码:
static func generatePostView(postItem: Post) -> UIView {
let postDescription: DefaultLabel = {
let lbl = DefaultLabel(labelFont: UIFont(name: "Montserrat-Medium", size: 16)!, labelTextColor: .black, labelText: "")
lbl.numberOfLines = 0
lbl.text = postItem.content.message
lbl.layer.borderWidth = 1
return lbl
}()
let postView = UIView()
postView.addSubview(postDescription)
postDescription.anchor(top: postView.topAnchor, left: postView.leftAnchor, bottom: nil, right: postView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
postDescription.sizeToFit()
postView.layoutSubviews()
return postView
}
如您所见,从 ViewComponentsBuilder 生成的 postView 没有包含其子视图(在这种情况下,它是一个包含帖子描述的标签;您看到的边框不是来自 postView,而是来自正确调整大小的标签它的高度根据内容)。这种行为会导致整个视图变砖。
我真的不知道问题出在哪里,非常感谢您提供一些建议。提前致谢!
【问题讨论】:
-
你在
DefaultLabel中实现了sizeThatFits:吗? -
没有。但是标签本身具有正确的 sizeToFit 行为?
-
我建议不要使用
sizeToFit。大约 6 年前,当我们从自动调整大小切换到自动布局时,这是一种旧方法,大部分已被其他方法取代。 -
感谢您的评论。还有哪些其他方法?
-
@linus_hologram
intrinsicContentSize并正确设置拥抱和压缩阻力。由于其固有尺寸,您的标签已经具有正确的尺寸,您只需为postView提供正确的约束。而且您已经找到了正确的解决方案:)
标签: ios swift uiview nslayoutconstraint ios-autolayout