繁体   English   中英

视图高度包装子视图内容

[英]View height wrap child views content

我想在超级视图的左侧添加一个图像,并在超级视图的自定义标签中心添加一个图像。 另外,superview的高度必须包裹孩子。 我也将Superview添加到堆栈中(填充,填充分布和对齐)。 代码在下面,但未显示imageview。 这是什么问题?

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

我认为您的问题出在backImageView Y约束中

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

应该

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

Y是垂直轴,所以在您的4个约束中,您有3个垂直约束和1个水平约束。 centerXAnchor替换它,您应该会很好。

在此处输入图片说明

暂无
暂无

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

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