2016-08-13 130 views
1

我試圖以編程方式創建一個UIViewUILabel作爲子視圖使用自動佈局。Autolayout - UIView無法正確調整子視圖的大小

約束

我用下面的約束上view

  • 的centerX的viewfastAttacksContainerView(上海華)

  • 頂部常數8對超視圖的約束。

  • 然後創建的label其是恆定8 view並加入約束一個子視圖,底部,和view

問題

view只調整大小以標籤的和不佔的恆定8上的所有4個側面的4個約束。這導致label部分顯示在view之外。

let view = UIView() 
view.backgroundColor = pokemon.secondaryColor 

let label = UILabel() 

fastAttacksContainerView.addSubview(view) 
view.translatesAutoresizingMaskIntoConstraints = false 

view.addSubview(label) 
label.translatesAutoresizingMaskIntoConstraints = false 

label.text = fa 

let gest = UITapGestureRecognizer(target: self, action: #selector(self.selectFastAttack)) 
view.addGestureRecognizer(gest) 

fastAttackButtons.append(view) 
fastAttackLables.append(label) 

let top = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .Top, multiplier: 1, constant: 8) 
let centerX = NSLayoutConstraint(item: view, attribute: .CenterX, relatedBy: .Equal, toItem: fastAttacksContainerView, attribute: .CenterX, multiplier: 1, constant: 0) 

let labLeft = NSLayoutConstraint(item: label, attribute: .Left, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 1, constant: 8) 
let labTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 8) 
let labRigth = NSLayoutConstraint(item: label, attribute: .Right, relatedBy: .Equal, toItem: view, attribute: .Right, multiplier: 1, constant: 8) 
let labBottom = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 8) 
view.addConstraints([labLeft, labTop, labRigth, labBottom]) 
fastAttacksContainerView.addConstraints([top, centerX]) 

輸出

Simulation

+0

爲什麼你不使用的故事板? – Igor

+0

上面提到的代碼將被迭代,因爲'view'的數量在運行時被獲取。 – an23lm

回答

0

view具有不明確的高度。

你應該添加約束的高度view或距離它的底部fastAttacksContainerView

+0

不**視圖**在**頂部**和+ **在**底部**上取得'label' + 8的高度? – an23lm

+0

嘗試用'label.addConstraints([labLeft,labTop,labRigth,labBottom])替換'view.addConstraints([labLeft,labTop,labRigth,labBottom])'' – Igor

+0

程序崩潰了'View層次結構沒有爲約束「錯誤。 – an23lm

0

我設法使在故事板類似的設置,並在複製的約束來解決這個問題

的事情,我改變了:

  • 使用LeadingTrailing,而不是LeftRight佈局屬性。
  • 對於labLeftlabRight約束,我互換itemtoItem。 (這對我來說似乎是一個錯誤,任何人都可以驗證嗎?)

代碼變化:

let labLeft = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 8) 
let labTop = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 8) 
let labRigth = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: label, attribute: .Trailing, multiplier: 1, constant: 8) 
let labBottom = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: label, attribute: .Bottom, multiplier: 1, constant: 8) 
相關問題