如何在UINavigationBar自定义titleView中使用自动布局 [英] How to use auto layout in a UINavigationBar custom titleView

查看:416
本文介绍了如何在UINavigationBar自定义titleView中使用自动布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



他们从未展示过如何执行此操作的示例。



当我尝试时,我得到了一个零大小的视图。



在界面构建器中,我创建一个UIView并添加一个UISearchBar和一个UIButton作为这样的补贴



[seachBar] - [按钮]



它变为零宽度。



有谁知道如何使用这个新功能?

解决方案

我将回答我自己的问题。



基本上,自动布局的工作方式与您期望的一样。然而,问题是每个元素要么需要约束来指定其宽度,要么需要指定其内在大小。例如,如果您使用uilabel替换搜索栏,则自定义标题视图将正确匹配标签。搜索栏显然没有固有的大小,因此需要控制其增长。



我在搜索栏后面放了一个uilabel并将其限制在搜索栏的顶部,底部,前导和后缘。我给了uilabel很多文本并设置它以便在文本太多时它会被截断。



当我运行应用程序时,搜索栏有一个非零宽度和更改为和横向将缩小和拉伸搜索栏根据需要。按钮仍会折叠到0宽度,但通过将压缩阻力设置为高于uilabel,可以轻松修复。



添加假UILabel是一种破解为此,我知道。我会接受任何替代方案...



这是一个示例项目。


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?

解决方案

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.

这篇关于如何在UINavigationBar自定义titleView中使用自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆