使用tabBar.topAnchor进行奇怪的布局

时间:2018-03-14 16:55:31

标签: ios swift nslayoutconstraint nslayoutanchor

我有几个子视图

    view.addSubview(collectionView)
    view.addSubview(pageControl)
    view.addSubview((tabBarController?.tabBar)!)
    view.addSubview(skipButton)
    view.addSubview(nextButton)

我尝试通过layoutAnchor进行布局。 (此时我将pageControl.bottomAnchor锚定到view.bottomAnchor)

   nextButton.anchorWithConstantsToTop(view.topAnchor, left: nil, bottom: nil, right:
        view.rightAnchor, topConstant: 16, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
    nextButtonTopAnchor = nextButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 0)
    nextButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
    nextButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
    skipButton.anchorWithConstantsToTop(view.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 16, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
    skipButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
    skipButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
    pageControl.anchorWithConstantsToTop(nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 28, bottomConstant: 0, rightConstant: 30) 

所以它工作得很好,当我在适当的位置旋转设​​备pageControl夹具enter image description here

但是如果尝试锚定pageControl.bottomAnchor = tabBarController?.tabBar.topAnchor而不是view.bottomAnchor那么在纵向方向上一切正常,但是当我旋转设备时会发生一些令人恼火的事情:pageControl上升enter image description here

此外,当我将表格横向定位到纵向背面时 它仍处于上方enter image description here

我想这个问题存在于pageControl.bottomAnchor = tabBarController?.tabBar.topAnchor字符串中,但我可以理解为什么?在横向方向仍然仍然是tabBar和pageControl仍然必须将其锚定到tabBar的topAnchor。也许有人知道这种行为是怎么回事?

1 个答案:

答案 0 :(得分:1)

问题出在这一行:

  

view.addSubview((tabBarController?.tabBar)!)

你不应该这样做。请删除它,然后在将当前视图控制器添加到UITabBarController后设置约束。这个候选样本将是viewWillAppear第一次执行。

如果以编程方式创建pageControl,则还应将其translatesAutoresizingMaskIntoConstraints属性设置为false(如注释中所述)。如果在故事板中创建控件,则不需要此步骤。