2016-12-05 52 views
2

如何以編程方式約束等寬和等高與多個views.I檢查谷歌,但不是完美的答案,通過自動佈局編程等寬和高度約束。如何在ios swift中以編程方式創建自動佈局等寬約束?

我的代碼看起來象下面這樣:

var countNoOfViews:Int = 3 
@IBOutlet var viewForRow1: UIView! 

override func viewDidLoad() { 
     super.viewDidLoad() 
self.specialButtonViewLeft() 
} 

func specialButtonViewLeft(){ 

    for i in 0..<countNoOfViews{ 
     var customView:UIView! 
     customView = UIView(frame: CGRect.zero) 
     customView.translatesAutoresizingMaskIntoConstraints = false 
     viewForRow1.addSubview(customView) 

     let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal,toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20.0) 

     let topConstraint = NSLayoutConstraint(item: customView, attribute: .top, relatedBy: .equal,toItem: self.viewForRow1, attribute: .top, multiplier: 1.0, constant: 0) 

     let bottomConstraint = NSLayoutConstraint(item: customView, attribute: .bottom, relatedBy: .equal,toItem: self.viewForRow1, attribute: .bottom, multiplier: 1.0, constant: 0) 

     let leadingConstraint = NSLayoutConstraint(item: customView, attribute: .leading, relatedBy: .equal, toItem: self.viewForRow1, attribute: .leading, multiplier: 1, constant: customLeadingSpaceLeft) 

     customLeadingSpaceLeft = customLeadingSpaceLeft + customViewWidth 

     arrayLeftBtnConstraints.append(widthConstraint) 

     if i == 0{ 
      customView.backgroundColor = UIColor.red 
     }else if i == 1{ 
      customView.backgroundColor = UIColor.green 
     }else if i == 2{ 
      leftViewVal = customLeadingSpaceLeft 
      customView.backgroundColor = UIColor.black 
     } 
     customView.alpha = 0.50 
     viewForRow1.addConstraints([widthConstraint, leadingConstraint,topConstraint,bottomConstraint]) 
    } 
} 

我希望通過編程添加寬度相等的約束。

+0

你能完成這項工作嗎? –

回答

2

嘗試這種情況:

let widthConstraint = NSLayoutConstraint(item: customView, attribute: .width, relatedBy: .equal, toItem: viewForRow1, attribute: .width, multiplier: 0.25, constant: 0.0) 

multiplier: 0.25,表示customView的寬度將是父視圖的1/4,viewForRow1

+0

Thanks.but我有多個視圖劃分相等的寬度超級view.and另一件事情,我想改變寬度的編程自動佈局約束基於方向像肖像 - 30和景觀-40寬度 –

0

您有三種可能的方式來做到這一點:

1)利用錨:

view.widthAnchor.constraint(equalTo: otherView.widthAnchor, multiplier: 1.0).isActive = true

2)可視格式:

簡單的例子 - "H:|[otherView]-[view(==otherView)]|"

3 )「老派」限制:

NSLayoutConstraint(item: #view, attribute: .width, relatedBy: .equal, toItem: #otherView, attribute: .width, multiplier: 1.0, constant: 0.0).isActive = true

希望它能幫助別人。

相關問題