2017-07-30 67 views
-3

我有一個視圖,我想要在它的超視圖中水平和垂直居中。如何在iOS Swift 3中以編程方式設置元素中心?

我試過,但它不工作:

let horConstraint = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0) 
view.addConstraints([horConstraint]) 

回答

1

試試這個:

注意:請確保您將此屬性設置爲false爲webView的

webView.translatesAutoresizingMaskIntoConstraints = false 
(應用約束前)

對於x軸

let horConstraint = NSLayoutConstraint(item: webView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX ,multiplier: 1.0, constant: 0.0) 

對於Y軸

let verConstraint = NSLayoutConstraint(item: webView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY ,multiplier: 1.0, constant: 0.0) 

view.addConstraints([horConstraint, verConstraint]) 
1

我建議嘗試使用這是更方便,更容易理解。此代碼以我的觀點爲中心:

let someView = UIView() 
    someView.backgroundColor = .red 
    someView.translatesAutoresizingMaskIntoConstraints = false 
    view.addSubview(someView) 
    someView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true 
    someView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 
    someView.heightAnchor.constraint(equalToConstant: 50).isActive = true 
    someView.widthAnchor.constraint(equalToConstant: 50).isActive = true 
相關問題