ios - 在 UIView 中心添加 UILabel

标签 ios swift xcode uiview

我的 UICollectionView 创建了一些自定义 UIView(称为 NumberView)

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

我做的是:

  1. 我在 UIViewController 中创建了 NumberViews

  2. 我在 NumberView 中创建标签

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

对于 (2),我在 NumberView 的初始化中执行此操作:

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 的中间?

最佳答案

您需要将布局 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/

相关文章:

ios - 如何将插图添加到 UILabel (iOS Swift)?

ipad - 使用 Instruments 分析 iPad/iPhone web 应用程序

ios - Tableview Swift 中的多个计时器

Swift 如何监听 AWS DynamoDB 中的更改

ios - 选择 DatePicker 后更新单元格中的日期(时间)

objective-c - 在 UITableViews 和 View 之间导航并保留数据?

iphone - 游戏中心即使没有 iTunes 连接

Swift - 解析 - friend 列表 - 可以创建 friend 组

iphone - 为什么在尝试安装 Ad-Hoc 构建时会出现 "could not be added to your itunes library because it is not a valid app"错误?

ios - 部署目标为 7.0 和 Xcode 7.1-7.2 的 iPhone4 中的启动屏幕为黑色