How to use auto layout in a UINavigationBar custom titleView

◇◆丶佛笑我妖孽 提交于 2019-12-10 15:00:25

问题


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.



来源:https://stackoverflow.com/questions/46324704/how-to-use-auto-layout-in-a-uinavigationbar-custom-titleview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!