2016-11-28 247 views
0

因此,我完成了Xcode中的IB並且想要在Swift中編寫所有UIIOS以編程方式在Swift中添加約束條件

所以我所做的就是:

  • 創建一個新的UIView包含我想寫的元素 -
  • 我添加TestViewVC爲讓稱它爲「TestView」子視圖。
  • TestView類我已經添加的元素是這樣的:

    class TestView: UIView { 
         var someLabel:UILabel! 
         override init(frame: CGRect) { 
          super.init(frame: frame) 
    
          self.someLabel = UILabel(frame: CGRect(x: self.frame.midX, y: oneSixthHeight, width: 100, height: 22)) 
          self.someLabel.text = "test" 
    
          var constraints:[NSLayoutConstraint] = [] 
          self.someLabel.translatesAutoresizingMaskIntoConstraints = false 
          let rightsideAnchor:NSLayoutConstraint = NSLayoutConstraint(item: self.someLabel, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 1) 
    
          constraints.append(rightsideAnchor) 
          NSLayoutConstraint.activateConstraints(constraints) 
         } 
    } 
    

有了這個,我期待UILabel錨定到視圖的右側。

不過,我得到這個錯誤:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items > and > because they have no common ancestor.
Does the constraint reference items in different view hierarchies? That's illegal.'

我在做什麼錯?

+0

你在哪裏添加someLabel爲您的視圖的子視圖?您只能應用約束,並在已添加爲子視圖時將其激活。否則嘗試會導致崩潰,你只看到 –

回答

4

只有在將視圖添加到視圖層次結構後,才應該添加約束。從你的代碼中可以清楚的看到你沒有添加UILabel實例來查看。

+1

賓果:)因此,投票:) –

+0

謝謝你! :)添加了標籤作爲子視圖,它都像一個魅力。 <3 –

+0

很高興它的工作。 – msk

3

更新了斯威夫特3約束

import UIKit 

class ViewController: UIViewController { 

let redView: UIView = { 

    let view = UIView() 
    view.translatesAutoresizingMaskIntoConstraints = false 
    view.backgroundColor = .red 
    return view 
}() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    setupViews() 
    setupAutoLayout() 
} 

func setupViews() { 

    view.backgroundColor = .white 
    view.addSubview(redView) 
} 

func setupAutoLayout() { 

    // Available from iOS 9 commonly known as Anchoring System for AutoLayout... 
    redView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true 
    redView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20).isActive = true 

    redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true 
    redView.heightAnchor.constraint(equalToConstant: 300).isActive = true 

    // You can also modified above last two lines as follows by commenting above & uncommenting below lines... 
    // redView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true 
    // redView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true 
} 
} 

enter image description here

類型:

/* 
// regular use 
1.leftAnchor 
2.rightAnchor 
3.topAnchor 
// intermediate use 
4.widthAnchor 
5.heightAnchor 
6.bottomAnchor 
7.centerXAnchor 
8.centerYAnchor 
// rare use 
9.leadingAnchor 
10.trailingAnchor 
etc. (note: very project to project) 
*/ 
相關問題