我正在尝试创建一个ViewBuilder类来设置视图并将其返回给调用者。然后,调用者只需约束一个包含一些子视图的视图,这些子视图在该视图内是受约束的。这样,我想保存一些代码。
使用代码,事情会变得更清楚:
我的“收藏夹视图单元”中的代码:
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,right: postView.rightAnchor,paddingLeft: 0,paddingRight: 0,height: 0)
postDescription.sizeToFit()
postView.layoutSubviews()
return postView
}
如您所见,从ViewComponentsBuilder生成的postView不会包含其子视图(在这种情况下,它是包含帖子说明的标签; 您看到的边框不是来自postView而是正确调整了标签的大小)其高度取决于内容)。此行为导致整个视图变砖。
我真的不知道问题出在哪里,并且非常感谢您提供一些建议。预先感谢!