视图高度包裹子视图内容

时间:2018-11-05 15:17:16

标签: ios swift autolayout intrinsic-content-size

我想在超级视图的左侧添加图像,并在超级视图的自定义标签中心添加一个图像。另外,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

1 个答案:

答案 0 :(得分:0)

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

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

应该是

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

Y用于垂直轴,因此在您的4个约束中,您具有3个垂直约束和1个水平约束。用centerXAnchor代替它,您应该会很好。

enter image description here