OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UIView 的中心添加 UILabel [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:24
标题: ios - 在 UIView 的中心添加 UILabel

我的 UICollectionView 创建了一些自定义 UIViews(称为 NumberViews)

每个 NumberView 都有一个属性 var text: UILabel! 这是一个标签,应该在 NumberView 的中间生成。

我做的是:

  1. 我在 UIViewController 中创建 NumberViews

  2. 我在 NumberViews 中创建标签

(1) 工作得很好,但 (2) 不行。它在 NumberView 之外的某个奇怪的地方创建标签。

对于(2),我在 NumberView 的 init 中这样做:

var text: UILabel!

override init(frame: CGRect) {
    super.init(frame: frame)
    self.text = UILabel(frame: frame)
    self.text.textAlignment = NSTextAlignment.center
    self.text.text = "testing"
    self.addSubview(self.text)
}

然后发生的事情是这样的:

               ______________    _
              |              |    \
              |     ______   |    |
 NumberView --|--> |      |  |    |
              |    |______|  |    |
              |              |    |
      Label --|----> testing |     > ViewController
              |              |    |
              |              |    |
              |              |    |
              |              |    |
              |______________|   _/

如何将标签移动到 NumberView 的中间?



Best Answer-推荐答案


您需要将布局 anchor 添加到您的 numberView 设置它的 center.x 和 center.y 等于标签的。

我现在不在 Mac 上,但您应该可以搜索代码来创建中心布局 anchor 。

快速搜索出现了这个网站:

http://useyourloaf.com/blog/pain-free-constraints-with-layout-anchors/

你要创建一个 centerXAnchor 和一个 centerYAnchor

关于ios - 在 UIView 的中心添加 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324557/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4