2016-03-11 162 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)