iOS在Swift

时间:2016-11-28 08:31:48

标签: ios swift nslayoutconstraint

所以,我完成了使用IB中的Xcode并希望在Swift中编写所有UI

所以我所做的是:

  • 创建了一个新的UIView来包含我想要编写的元素 - 让我们调用它" TestView"
  • 我已将TestView添加到VC作为子视图。
  • 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锚定在视图的右侧。

但是,我确实收到了这个错误:

  

由于未捕获的异常终止应用程序' NSGenericException',       原因:'无法使用项目激活约束>和>因为他们没有共同的祖先       约束是否引用不同视图层次结构中的项目?这是非法的。'

我做错了什么?

2 个答案:

答案 0 :(得分:6)

只有在将视图添加到视图层次结构后才应添加约束。从您的代码中可以清楚地看出,您尚未添加要查看的UILabel实例。

答案 1 :(得分:3)

针对Swift 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)
*/