在swift中以编程方式向工具栏添加按钮

在swift中以编程方式向工具栏添加按钮

本文介绍了在swift中以编程方式向工具栏添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在swift中向工具栏添加一个按钮,下面你可以看到我正在使用的工具栏图像,不幸的是即使我在Storyboard文件中设计了它,它也没有将工具栏设置为可见时显示。

I'm having a hard time adding a button to the toolbar in swift, below you can see an image of the toolbar that I'm after, unfortunately even though I have it designed in my Storyboard file, it doesn't show up when setting the toolbar to be visible.

我设计的方式是两个项目,第一个是灵活空间元素,第二个是 add 元素。它看起来像这样:

The way that I have designed this is two items, the first being a flexable space element, and the second being an add element. It looks like this:

这是代码我曾经试图在代码中复制它:

Here's the code that I've used to attempt to replicate this in code:

self.navigationController?.toolbarHidden = false
self.navigationController?.toolbarItems = [UIBarButtonItem]()
self.navigationController?.toolbarItems?.append(
    UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
)
self.navigationController?.toolbarItems?.append(
    UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onClickedToolbeltButton:")
)

如您所见,我将工具栏设置为可见,初始化(和清除)UIBarButtonItem的toolbarItems数组,然后将两个UIBarButtonItem添加到数组,按正确的顺序。

As you can see I'm setting the toolbar to be visible, initializing (and clearing) the toolbarItems array of UIBarButtonItem, and then adding two UIBarButtonItem's to the array, in the proper order.

但是,th e工具带仍然是空的,这是为什么?

However, the toolbelt remains empty, why is this?

推荐答案

通常的做法是创建工具栏项数组,然后将数组分配给 items 工具栏的属性。

The usual way to do that is to create the array of toolbar items and then assign the array to the items property of the toolbar.

self.navigationController?.isToolbarHidden = false
var items = [UIBarButtonItem]()
items.append(
    UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
)
items.append(
    UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(onClickedToolbeltButton(_:)))
)
self.navigationController?.toolbar.items = items

这篇关于在swift中以编程方式向工具栏添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:44