简体   繁体   English

视图高度包装子视图内容

[英]View height wrap child views content

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. 另外,superview的高度必须包裹孩子。 Also I am adding superview in to a stack(fill,fill distribution and alignment ). 我也将Superview添加到堆栈中(填充,填充分布和对齐)。 Code is below but imageview not showing. 代码在下面,但未显示imageview。 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

I think your problem is in the backImageView Y constraint 我认为您的问题出在backImageView Y约束中

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. Y是垂直轴,所以在您的4个约束中,您有3个垂直约束和1个水平约束。 Replace it with a centerXAnchor and you should be good. centerXAnchor替换它,您应该会很好。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM