【问题标题】:View height wrap child views content视图高度换行子视图内容
【发布时间】:2019-04-08 23:25:14
【问题描述】:

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

【问题讨论】:

  • 抱歉,如果这是一个愚蠢的问题,但您是否将您的 topView 添加到 self.view?此外,您的顶视图缺少 2 个约束,例如 centerX 和 centerY
  • 是的,我将它添加到堆栈视图中,并将堆栈视图添加到超级视图中。标签显示但图像视图未显示。

标签: ios swift autolayout intrinsic-content-size


【解决方案1】:

我认为你的问题在于backImageView Y 约束

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

应该是

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

Y 代表 vertical 轴,因此在您的 4 个约束中,您有 3 个垂直约束和 1 个水平约束。将其替换为centerXAnchor,您应该会很好。

【讨论】:

  • 我想在父视图的左侧而不是父视图的中心添加图像视图
  • 问题是您的UIImageView 没有显示,这是一个限制问题。现在显示出来了。如果你想把它放在左边,把 topbottomleft 粘贴到 superview 上,然后分配一个 width i> 不变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 2017-12-07
相关资源
最近更新 更多