How to use auto layout in a UINavigationBar custom

2019-06-23 17:41发布

问题:

In WWDC 2017 presentation 204 they say that you can use autolayout in the custom titleView.

It happens around 7:53

They never show an example of how to do this.

When I try, I get a zero sized view.

In interface builder I create a UIView and add a UISearchBar and a UIButton as subsides kind of like this

[seachBar]-[Button]

It becomes zero width.

Does anyone know how to use this new feature?

回答1:

I'll be answering my own question.

Essentially, auto layout works like you would expect. However, the gotcha is that every element either needs to have constraints to specify its width or it needs its intrinsic size specified. For example, if you replaced the search bar with a uilabel, the custom title view would fit the label correctly. The search bar does not have intrinsic size apparently so something needs to control its growth.

I put a uilabel behind the search bar and constrained it to the search bar's top, bottom, leading, and trailing edges. I gave the uilabel ALOT of text and set it so that it would truncate when there is too much text.

When I ran the app, the search bar had a non-zero width and changing to and from landscape would shrink and stretch the search bar as desired. The button would still collapse to 0 width, but it is easily fixed by setting the compression resistance higher than the uilabel.

It is kind of a hack to add a dummy UILabel for this purpose, I know. I'd be open to any alternatives...

Here is an example project.