从xib加载并将自动调整大小的蒙版转换为约束

时间:2018-08-19 09:09:17

标签: ios swift

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var vsuper: UIView!
override func viewDidLoad() {
    super.viewDidLoad()
    let  v = view2.getView()

    vsuper.backgroundColor = UIColor.black
    vsuper.addSubview(v)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// xib文件

import UIKit

class view2: UIView {

override func awakeFromNib() {
    super.awakeFromNib()
}
static func getView()->view2{
    let v = Bundle.main.loadNibNamed("view2", owner: nil, options: nil)?.first as! consentview
   // v.translatesAutoresizingMaskIntoConstraints = false
    return v;
}

}

虽然我将xib加载到情节提要中的另一个视图中,但是如果将translateautoresizingmaskintoconstraints设置为false,则不会将其添加到该视图中,但是如果我删除该行,它将被添加到该视图中。

如果将其设置为false,它将在左上方占用空间,否则将被添加到视图中。为什么这样 ?即使我将其添加到超级电视

2 个答案:

答案 0 :(得分:0)

尝试

 import UIKit

 class MyView: UIView {

    // your outlets from your view can be there

    // your functions for your view
    func myFunc() {

    }
 }


import UIKit

class ViewController: UIViewController {

   var myView: MyView!

   override func viewDidLoad() {
      super.viewDidLoad()

      if let contentView = Bundle.main.loadNibNamed("MyView", owner: self, options: nil)?.first as? MyView {

        myView = contentView
        self.view.addSubview(myView)

      }

      // set background color your custom view
      myView.backgroundColor = UIColor.black

      // call functions for your custom view
      myView.myFunc()

   }
}

答案 1 :(得分:0)

您没有设置约束。 translatesAutoresizingMaskIntoConstraints = false表示您不希望将xib框架转换为约束,因此您可以自己设置约束。这就是为什么它没有为您的超级视图上的xib视图分配任何范围的原因。在addSubview()调用之后,尝试对Superview进行一些约束。例如

v.leadingAnchor.constraint(equalTo: vsuper.leadingAnchor, constant: 0).isActive = true
v.trailingAnchor.constraint(equalTo: vsuper.trailingAnchor, constant: 0).isActive = true
v.topAnchor.constraint(equalTo: vsuper.topAnchor, constant: 0).isActive = true
v.bottomAnchor.constraint(equalTo: vsuper.bottomAnchor, constant: 0).isActive = true
vsuper.layoutIfNeeded()