UIViewController:调整xib的约束

时间:2015-05-15 14:20:26

标签: ios swift constraints

在我的项目中,我定义了一个xib和一个包含xib的ViewController。

class FeedDetailViewController: UIViewController, FeedDetailDelegate {

  var feedDetail: FeedDetail!

  override func viewDidLoad() {
    super.viewDidLoad()
    feedDetail = (NSBundle.mainBundle().loadNibNamed("FeedDetail", owner: self, options: nil)[0] as? UIView)! as! FeedDetail
    feedDetail.delegate = self;
    self.view.addSubview(feedDetail)
    self.adjustContraints()
  }

 func adjustContraints() { 

    feedDetail.sizeThatFits(self.view.frame.size)

    var constraint = NSLayoutConstraint(item: feedDetail,
        attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
    view.addConstraint(constraint)

    constraint = NSLayoutConstraint(item: feedDetail,
        attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
    view.addConstraint(constraint)

    constraint = NSLayoutConstraint(item: feedDetail,
        attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)
    view.addConstraint(constraint)

    constraint = NSLayoutConstraint(item: feedDetail,
        attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
    view.addConstraint(constraint)

    self.view.layoutIfNeeded()

}

我想要的只是“全屏”的xib,但是xib边框不会“粘在”控制器的主视图上。

enter image description here

边境传奇:

  • red:self.view
  • 黄色:feedDetail
  • 其他:feedDetail中的元素(仅限测试)

1 个答案:

答案 0 :(得分:2)

尝试在添加约束之前调用此方法。

feedDetail.setTranslatesAutoresizingMaskIntoConstraints(false)