Adding Constraint messed up view

2019-08-23 04:25发布

问题:

I have a view with a UICollectionView and a UISegmentedControl.

I want to change constraints so the segment controller won't overlap collection view, like in this picture:

This is my code :

override func viewDidLoad()
    {
        super.viewDidLoad()

        self.navigationItem.leftBarButtonItem = nil
        self.tabBarController?.tabBar.isHidden = true


        self.SegmentController.setTitle(SegmentAtext, forSegmentAt: 0)
        self.SegmentController.setTitle(SegmentBtext, forSegmentAt: 1)


        self.view.bringSubview(toFront: SegmentController)

        self.LoadProducts(productsToShow: SegmentAtype)
    }

SO I add this command:

self.ProductsCollection.topAnchor.constraint(equalTo: SegmentController.bottomAnchor, constant: 10).isActive = true

But the result is worse:

Now the segment controller is almost completely hidden!

How do I fix this?

Edit:

My viewDidLayoutSubviews function:

override func viewDidLayoutSubviews()
    {
        ProductsCollection.translatesAutoresizingMaskIntoConstraints = false
        let topConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
        let bottomConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -50) //leaving space for search field
        let leadingConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: ProductsCollection, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)

        self.view.addConstraints([topConstraint, bottomConstraint, leadingConstraint, trailingConstraint])
    }

Notice:

my viewDidLayoutSubviews is implemented in the super view, which does not contain a UISegmentedControl. the UISegmentedControl is contained in an inheriting view.

Edit: An updated view

回答1:

If you would want the UISegmentedControl to be centred on the screen and below it to have your collection view you would do

NSLayoutConstraint.activate([
    segmentedControl.topAnchor.constraint(equalTo: view.topAnchor),
    segmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
    collectionView.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor),
    collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
    collectionView.rightAnchor.constraint(equalTo: view.rightAnchor),
    collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])

So we have segmented controls top be top of the view, and center it, then top of collection view is bottom of segmented control (you can add a constant for padding if needed) and left right and bottom to the view