简体   繁体   English

您可以在Interface Builder中使用自定义视图创建UIBarButtonItem吗?

[英]Can you create a UIBarButtonItem with a Custom View in Interface Builder

I know how to use initWithCustomView to create and add a UIBarButtonItem with a custom view in code. 我知道如何使用initWithCustomView在代码中创建和添加带有自定义视图的UIBarButtonItem。 But I prefer to do things like this in Interface Builder when I can. 但我喜欢在Interface Builder中做这样的事情。 I can't seem to find any way to create a custom UIBarButtonItem and set the custom view. 我似乎找不到任何方法来创建自定义UIBarButtonItem并设置自定义视图。

OK, I eventually figured out how to do it. 好的,我最终想出了怎么做。

If you drag a view onto a NavigationItem that will create a UIBarButtonItem that is initialized with that custom view and it links it to the right bar button. 如果将视图拖动到NavigationItem上,NavigationItem将创建使用该自定义视图初始化的UIBarButtonItem,并将其链接到右侧栏按钮。 Alternatively you can drag the view onto a bar button item that is inside a Navigation Item. 或者,您可以将视图拖动到导航项目内的条形按钮项目。 It will not work for a bar button item that is not inside a Navigation Item. 它不适用于不在导航项内的条形按钮项。

To create a left bar item with custom view, it is a bit trickier. 要使用自定义视图创建左栏项目,它有点棘手。 A bar button item inside a navigation item is hardcoded to be the right side item. 导航项目内的条形按钮项目被硬编码为右侧项目。 What I did was add another navigation item temporarily to the top level of the xib file. 我所做的是临时将另一个导航项添加到xib文件的顶层。 Then drag the view onto the navigation item which creates the bar button item inside this navigation item. 然后将视图拖动到导航项目上,该导航项目在此导航项目中创建栏按钮项目。 Move the bar button item out of the navigation item (to the top level of the xib). 将栏按钮项移出导航项(到xib的顶层)。 Then I can delete the navigation item I added so then I have a free standing bar button item initialized with a custom view. 然后我可以删除我添加的导航项,然后我有一个用自定义视图初始化的独立栏按钮项。 You then have to add the link from the leftBarButtonItem outlet of the real navigation item to this bar button item yourself. 然后,您必须自己将实际导航项的leftBarButtonItem插座中的链接添加到此栏按钮项。

As he said in the comments, user486646's solution no longer works in Xcode 6. After messing around a bit this is what I figured out. 正如他在评论中所说,user486646的解决方案不再适用于Xcode 6.稍微搞了一下这就是我想到的。

1) Drag a toolbar into your View Controller Scene. 1)将工具栏拖到View Controller Scene中。 Not into the view, but into the scene, eg. 不是进入视图,而是进入场景,例如。 under Exit. 退出。

2) Drag your custom view into (under) the toolbar. 2)将自定义视图拖到工具栏的(下方)。 This will create the the UIBarButtonItem with embedded custom view in the toolbar. 这将在工具栏中创建带有嵌入式自定义视图的UIBarButtonItem。

3) Now drag the the UIBarButtonItem with embedded custom view to wherever you really want it (eg. navigation item or just as one of the View Controller's toolbar items). 3)现在将带有嵌入式自定义视图的UIBarButtonItem拖动到您真正想要的位置(例如导航项或仅作为View Controller的工具栏项之一)。

4) Delete the toolbar created in step 1. 4)删除在步骤1中创建的工具栏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM