View height wrap child views content

222 views Asked by At

I want to add a image left of the super view and a custom label center of the superview. Also superview's height must wrap children. Also I am adding superview in to a stack(fill,fill distribution and alignment ). Code is below but imageview not showing. What is problem here?

let topView = UIView()
topView.translatesAutoresizingMaskIntoConstraints = false
topView.heightAnchor.constraint(equalToConstant: 30).isActive = true
topView.widthAnchor.constraint(equalToConstant: self.view.frame.size.width).isActive = true

let backImageView: UIImageView = UIImageView()
backImageView.isUserInteractionEnabled = true
backImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
backImageView.image = UIImage(named: "backButton")
backImageView.contentMode = .scaleAspectFit
backImageView.clipsToBounds = true

topView.addSubview(backImageView)
backImageView.leftAnchor.constraint(equalTo: topView.leftAnchor).isActive = true
backImageView.topAnchor.constraint(equalTo: topView.topAnchor).isActive = true
backImageView.bottomAnchor.constraint(equalTo: topView.bottomAnchor).isActive = true
backImageView.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true

topView.addSubview(titleText)
titleText.centerXAnchor.constraint(equalTo: topView.centerXAnchor).isActive = true
titleText.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true
1

There are 1 answers

2
Crocobag On

I think your problem is in the backImageView Y constraint

backImageView.centerYAnchor.constraint(equalTo: topView.centerYAnchor).isActive = true

should be

backImageView.centerXAnchor.constraint(equalTo: topView.centerXAnchor).isActive = true

the Y is for vertical axix, so in your 4 contraints you have 3 vertical constrains, and 1 horizontal constraint. Replace it with a centerXAnchor and you should be good.

enter image description here