【发布时间】:2017-03-04 06:11:10
【问题描述】:
我花了几个小时试图找出阻止我的约束布局工作的原因。我有一个名为 ABSegment 的视图,它只包含一个 UILabel,它应该居中并具有与其父视图相同的高度和宽度。
我将包含此 UIView 子视图的整个类定义以显示我所做的。
import UIKit
class ABSegment: UIView {
let titleLabel = UILabel()
init(withTitle title: String) {
titleLabel.text = title
titleLabel.textAlignment = .center
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLabel)
backgroundColor = UIColor.blue
}
override func layoutSubviews() {
super.layoutSubviews()
logFrames()
}
func logFrames() {
print("self.frame is \(frame)")
print("titleLabel.frame is \(titleLabel.frame)")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
logFrames()
titleLabel.removeConstraints(titleLabel.constraints)
let centerX = NSLayoutConstraint(item: titleLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)
let centerY = NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([centerX, centerY, width, height])
super.updateConstraints()
}
}
很自然地怀疑我没有用 initWithFrame 初始化这个视图。相反,我将框架设置推迟到构建这些视图的代码的后面。所以构造这些的代码不会设置框架。框架可以在 Storyboard 中设置或像这样:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let frame = CGRect(x: view.bounds.origin.x + 150, y: view.bounds.origin.y + 200, width: 100, height: 100)
segment.frame = frame
segment.layoutSubviews()
}
我的理解是,由于我正在调用segment.layoutSubviews(),因此 ABSegment 视图应该进行更改以将先前激活的约束应用于最终帧。
有很多不同的设置和事情要按照正确的顺序正确处理,除了根本看不到标签出现之外,没有任何反馈。
【问题讨论】:
标签: swift uiview autolayout constraints