激活约束时,是相对于视图的父视图还是超级视图的约束?

时间:2017-08-28 07:52:13

标签: ios swift autolayout nslayoutconstraint swift4

我有三个观点:

  1. 超级视图
  2. superview中的UIScrollView
  3. UIScrollView中的UIView
  4. 我试图通过NSLayoutConstraint.constraints(withVisualFormat :)使用Visual Format字符串来定义UIView和它的父视图UIScrollView之间的自动布局关系。但是,当我通过NSLayoutConstraint.activate()激活约束时,约束似乎是相对于超级视图而不是UIView的父视图(UIScrollView)。

    我认为约束是根据视图的父视图激活的,但我找不到任何文档来定义视图的父视图或视图的超级视图之间的关系

    如果约束是相对于superview的,有没有办法定义相对于父视图的约束?

    谢谢!

    class MainVC: UIViewController {
    
    var scrollView = UIScrollView()
    var centerVC = CenterVC()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        scrollView.frame = CGRect(x: 0, y: 70, width: self.view.frame.width*0.8, height: self.view.frame.height - 120.0)
        self.view.addSubview(scrollView)
    
        centerVC.willMove(toParentViewController: self)
        self.addChildViewController(centerVC)
        centerVC.didMove(toParentViewController: self)
    
        let centerVCView: UIView = centerVC.view
    
        scrollView.addSubview(centerVCView)
    
        let slideViews: [String: UIView] = ["centerVCView" : centerVCView]
        let centerVCHorizontalConstraint = "H:|[centerVCView]|"
        let centerVCVerticalConstraint = "V:|[centerVCView]|"
        centerVCView.translatesAutoresizingMaskIntoConstraints = false
    
        var slideViewConstraints : [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: centerVCHorizontalConstraint, options: [], metrics: nil, views: slideVCViews)
        slideViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: centerVCVerticalConstraint, options: [], metrics: nil, views: slideVCViews)
    
        NSLayoutConstraint.activate(slideViewConstraints)
    }}
    

0 个答案:

没有答案