[英]Get frame size in updateConstraint function of Custom UIView
我在下面的UpdateConstraint
函数中的自定义UIView
设置视图约束( UILabel
, UIImageView
)。 如图所示,我正在获取视图的高度并将其在自动布局内使用。 我知道我可以在layoutSubviews
函数中获取帧大小。 如果我在layoutSubViews
内部调用updateConstraint()
函数,则一切正常,但我不知道这是否是最佳方法。
另外,当我尝试使用label.frame = CGRect..
(没有自动布局)在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()
}
我搜索了以下帖子,但找不到任何解决方案;
如果当前约束创建扩展集isActive = true
则无需在layoutSubviews
处理该问题,它将具有正确的框架
//
创建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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.