2016-11-28 128 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) 
*/ 
相关问题