robb / Cartography

A declarative Auto Layout DSL for Swift :iphone::triangular_ruler:
Other
7.35k stars 525 forks source link

Aligning Items to Navigation Bar #244

Closed erenkabakci closed 2 years ago

erenkabakci commented 7 years ago

I am not sure if I miss something here or it is not clear in cartography. Correct me if I am wrong.

|---------------|
|               | <- navBar
|---------------|
|               | <- searchBar
|---------------|
|               |
|               |
|               |
|---------------|

This is a common case with a navigation bar and any view/view controller in every ios app.

Any layout using top here will cause problems since if you align any item's top with superView.top, it will go under navBar.

Using topLayoutGuide is an option here but the way we update is kind of an overkill.

var topLayoutConstraint: NSLayoutConstraint!

build the constraints

constrain(searchBar) { searchBar in
        guard let superView = searchBar.superview else {
            return
        }
        topLayoutConstraint = searchBar.top == superView.top
        searchBar.left == superView.left
        searchBar.right == superView.right
    }

and update the desired constraint in viewDidLayoutSubviews

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    topLayoutConstraint.constant = topLayoutGuide.length
}

This works but it is an overkill for a simple and common thing.

I came across topLayoutGuideCartography and bottomLayoutGuideCartography while looking for a random solution. Assigning them directly to the searchBar.Top does the magic without overriding viewDidLayoutSubviews or updating any constraints in a later time.

constrain(searchBar) { searchBar in
        guard let superView = searchBar.superview else {
            return
        }
        searchBar.top == topLayoutGuideCartography
        searchBar.left == superView.left
        searchBar.right == superView.right
    }

If this is their designated use case. They should be mentioned in the README. This is a very common layout problem and SO is full of them. If needed I can open a PR for that.

If this is just a coincidence, I would like to know the right answer.

Thanks !

orta commented 7 years ago

Sounds like a good thing for the README - yep