0
votes

I'm setting constraints for views (UILabel, UIImageView) in custom UIView inside UpdateConstraint functions like below. As seen, I'm getting views' height and use it inside auto layout. I know I can get frame size in layoutSubviews function. If I call updateConstraint() function inside layoutSubViews , everything works fine but I don't know If It is the best approach.

In addition when I try to set frame in layoutSubViews() with label.frame = CGRect.. (without auto layout) nothing happens and I can't see custom views inside superview.

    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()
}

I searched below posts but can't find any solution;

Where to get frame size of custom UIView in its subclass

Subview of Custom UIView has wrong x frame position

1

1 Answers

0
votes

No need to handle that in layoutSubviews if your current constraint create extension sets isActive = true then it will have the correct frame

//

correct way of creating a 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

        }

    }
}