2015-06-19 64 views
0

如何爲所有設備製作標籤自動佈局。如何以編程方式製作此自動佈局?

 golabel = UILabel(frame: CGRectMake(30, 100, 350, 100)) 
     golabel.text = "Game Over" 
     golabel.textColor = UIColor.whiteColor() 
     golabel.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 70) 
     self.view.addSubview(golabel) 
+0

Autolayout關於將您的視圖與其他視圖相關聯。如果你沒有解釋它應該如何與你的界面相關聯是不可能給你的答案 – Andrea

+0

我希望它被放置在中心的上方 – tanman

+0

X或Y中心?或兩者? – Andrea

回答

1
let golabel = UILabel() 

golabel.setTranslatesAutoresizingMaskIntoConstraints(false) 

let horizontalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 30) 
view.addConstraint(horizontalConstraint) 

let verticalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 100) 
view.addConstraint(verticalConstraint) 

let widthConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 350) 
golabel.addConstraint(widthConstraint) 

let heightConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100) 
golabel.addConstraint(heightConstraint) 
+0

水平和垂直都有錯誤。 – tanman

+0

檢查更新的代碼.. :) –

0

後您添加的標籤,因爲你需要避免自動佈局,以自動尺寸口罩轉化爲約束的子視圖或者你可能會有衝突。

golabel.setTranslatesAutoresizingMaskIntoConstraints(false) 

此處添加了限制

let horizontalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) 
    self.view.addConstraint(horizontalConstraint) 

let verticalConstraint = NSLayoutConstraint(item: golabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0) 
    self.view.addConstraint(verticalConstraint) 

既然你不加抑制的標籤種植標籤將使用其內在的內容大小的限制,因此它可以增長無限期根據長度和文本的字體。

相關問題