2016-03-11 126 views
0

我有一个简单的UIView子类包含一个标签。这个子类有以下init方法:垂直对齐一个标签与PureLayout

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

什么是PureLayout?它是否有自动布局库? –

+0

@BharatModi https://github.com/PureLayout/PureLayout – AppsDev

回答

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)