【问题标题】:Swift: Align view X points from center towards trailing edgeSwift:将视图 X 点从中心对齐到后缘
【发布时间】:2021-11-09 07:10:07
【问题描述】:

我有一个 UIImageView,它应该放置在距父 UIView 中心 10 个点的位置。在 LTR 中它可以正常工作,但在 RTL 中它应该是 -10 点。

有没有办法将 X 点从中心对齐到后缘?还是应该根据布局方向手动设置约束?

【问题讨论】:

  • 你确定要让UIImageView在基于UIView的中心,左10右10?

标签: swift autolayout right-to-left


【解决方案1】:

如果您将图像视图的 Leading 锚点约束到视图的 CenterX 锚点,使用 Constant: 10,它将自动切换到其 CenterX-10 pts 的尾随锚点。

您可以通过以下代码做到这一点:

    let imgView = UIImageView()
    imgView.backgroundColor = .systemYellow
    imgView.translatesAutoresizingMaskIntoConstraints = false
    if let img = UIImage(systemName: "person") {
        imgView.image = img
    }
    view.addSubview(imgView)
    let g = view.safeAreaLayoutGuide
    NSLayoutConstraint.activate([
        imgView.topAnchor.constraint(equalTo: g.topAnchor, constant: 100.0),
        imgView.widthAnchor.constraint(equalToConstant: 120.0),
        imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor),
        imgView.leadingAnchor.constraint(equalTo: g.centerXAnchor, constant: 10.0),
    ])

这是它在 Storyboard 中的外观(垂直的红线只是显示水平中心的 1 磅宽的视图):

在运行时,使用 RTL 语言(完全没有代码):

【讨论】:

  • 是的,可能会按照您的建议进行。我目前有图像中心来查看中心+ 10 约束。知道图像的宽度后,我可以按照您所说的通过指向中心来对齐它。谢谢
【解决方案2】:

translatesAutoresizingMaskIntoConstraints 用于将约束调整为代码。

您还应该为顶部和底部添加约束。

@IBOutlet weak var myImageView: UIImageView!

...

override func viewDidLoad() {
  super.viewDidLoad()
  myImageView.translatesAutoresizingMaskIntoConstraints = false
  myImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
  myImageView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
  myImageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 10).isActive = true
}
...

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 2021-06-30
    • 2011-11-10
    • 2019-12-27
    • 2013-05-30
    • 1970-01-01
    • 2021-09-20
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多