在Custom UIView的updateConstraint函数中获取帧大小

时间:2018-05-21 12:02:05

标签: ios swift uiview frame cgrect

我在UILabel函数内的自定义UIImageView中为视图(UIViewUpdateConstraint)设置了约束,如下所示。如上所见,我得到的意见和#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()
}

我搜索了以下帖子,但无法找到任何解决方案;

Where to get frame size of custom UIView in its subclass

Subview of Custom UIView has wrong x frame position

1 个答案:

答案 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

        }

    }
}