0

我想添加超级视图左侧的图像和超级视图的自定义标签中心。超级视图的高度也必须包裹孩子。我还将超级视图添加到堆栈中(填充、填充分布和对齐)。代码如下,但 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
4

1 回答 1

0

我认为您的问题在于backImageViewY 约束

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

应该

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

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

在此处输入图像描述

于 2018-11-05T16:09:09.483 回答