我在 UIStoryboard
中添加一个 UIView
并将其绑定(bind)到一个名为 testView 的自定义 UIView
类,接下来,我创建一个 UIView
在 require init 函数中在 textView 中调用了 circelView ,然后我在 circelView 中创建了两个 UILabel
这是我的步骤
- 初始化circelView
- 将自动布局添加到circelView
- 创建两个
UILabel
并将它们添加到circelView - 将 AutoLayout 添加到两个
UILabel
然后我运行应用程序,我可以在当前位置找到 subview ,但是我在屏幕中找不到两个UILabel
,会发生什么?
这是我的代码:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
circelView = UIView()
self.addSubview(circelView)
circelView.snp_makeConstraints(closure: { (make) -> Void in
make.size.equalTo(80)
make.top.equalTo(self.snp_top)
make.right.equalTo(self.snp_right)
})
titleLabel = UILabel()
titleLabel.textColor = colorffffff
titleLabel.backgroundColor = UIColor.yellowColor()
titleLabel.font = font32
titleLabel.text = "hello"
titleLabel.numberOfLines = 1
titleLabel.backgroundColor = UIColor.yellowColor()
titleLabel.textAlignment = NSTextAlignment.Center
circelView.addSubview(titleLabel)
titleLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(circelView.snp_center)
}
detailLabel = UILabel()
detailLabel.textColor = colorffffff
detailLabel.font = font24
detailLabel.text = "hello"
titleLabel.numberOfLines = 1
detailLabel.textAlignment = NSTextAlignment.Center
detailLabel.addSubview(titleLabel)
detailLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(titleLabel.snp_bottom).offset(3)
make.centerX.equalTo(titleLabel.snp_centerX)
}
}
最佳答案
有一些原因可能导致此问题:
你的字体有多大?如果您的字体太大,而 View 太小(本例中为 80x80),则可能无法呈现文本。
在自动布局中,最好让 View 的大小基于其内容,而不是明确的(即 80x80)。通过将标签固定到其所有边缘的 super View ,您可以让“circelView”的大小根据其内容(两个标签)动态变化。为了保持“circelView”的“圆形”方面,您可以将“circelView”的高度限制为与其宽度相同。
归根结底,这需要更多的调试。我建议检查 View 层次结构以查看标签的位置。 Check out the documentation here.
关于iOS AutoLayout 工作出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34201361/