我有一个包含标签的简单UIView子类。该子类具有以下init方法:
override init(frame: CGRect) {
super.init(frame: frame)
self.autoSetDimension(.Height, toSize: 44)
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
self.addSubview(titleLabel)
titleLabel.text = "Some text"
titleLabel.sizeToFit()
titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: 20)
titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 20)
titleLabel.autoAlignAxisToSuperviewAxis(.Horizontal)
}
实际上,标签的文字可能会在运行时发生变化,但无论如何,当我运行应用程序时,我看不到标签在其父视图中垂直居中...有人可以帮助我吗?
提前致谢
答案 0 :(得分:0)
看到这个,如果它可以帮到你,
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Some dummy text"
self.view.addSubview(label)
let centreH = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 1)
let centreV = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 1)
self.view.addConstraint(centreH)
self.view.addConstraint(centreV)