我在UILabel
函数内的自定义UIImageView
中为视图(UIView
,UpdateConstraint
)设置了约束,如下所示。如上所见,我得到的意见和#39;高度并在自动布局中使用它。我知道我可以在layoutSubviews
函数中获得帧大小。如果我在updateConstraint()
内拨打layoutSubViews
功能,一切正常,但我不知道如果这是最佳方法。
此外,当我尝试使用layoutSubViews()
在label.frame = CGRect..
设置框架时(没有自动布局)没有任何反应,我无法在超级视图中看到自定义视图。
override func updateConstraints() {
logoImage.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: self.frame.height / 2, rightConstant: 0, widthConstant: 0, heightConstant: 0)
label.anchor(self.logoImage.bottomAnchor, left: self.leftAnchor, bottom: nil, right: self.rightAnchor, topConstant: 12, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
super.updateConstraints()
}
override func layoutSubviews() {
print(self.frame.height)
updateConstraints()
}
我搜索了以下帖子,但无法找到任何解决方案;
答案 0 :(得分:0)
如果当前约束创建扩展集layoutSubviews
,那么无需在isActive = true
中处理它,那么它将具有正确的框架
//
创建customView的正确方法
class CustomView : UIView {
var imageV = UIImageView()
var once = true
override init(frame: CGRect) {
super.init(frame: frame)
sharedLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedLayout()
}
func sharedLayout() {
// set constraints here
self.addSubview(imageV)
}
override func layoutSubviews() {
if once {
self.imageV.translatesAutoresizingMaskIntoConstraints = false
self.imageV.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
self.imageV.trailingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
self.imageV.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.imageV.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
once = false
}
}
}