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

Hob*_*ist 14 ios swift

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

我设计这个的方式是两个项目,第一个是flexable space元素,第二个是add元素.它看起来像这样:

在此输入图像描述

这是我用来尝试在代码中复制它的代码:

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:")
)
Run Code Online (Sandbox Code Playgroud)

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

但是,工具带仍然是空的,为什么会这样呢?

Dav*_*eek 30

以上都不适合我,但是:

Swift 3/Swift 4

self.navigationController?.isToolbarHidden = false

var items = [UIBarButtonItem]()

items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )
items.append( UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) ) // replace add with your function

self.toolbarItems = items // this made the difference. setting the items to the controller, not the navigationcontroller
Run Code Online (Sandbox Code Playgroud)

  • 这是有效的,但真正的问题是他们其余的人在做什么? (5认同)

vad*_*ian 17

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

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(_:)))
)
toolbarItems = items
Run Code Online (Sandbox Code Playgroud)


Uly*_*ses 6

self.navigationController?.toolbarItems = items

self.navigationController?.setToolbarItems(items, animated: false)

self.navigationController?.toolbar.setItems(items, animated: false)
Run Code Online (Sandbox Code Playgroud)

试试吧.

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

        self.navigationController?.toolbar.setItems(items, animated: false)
Run Code Online (Sandbox Code Playgroud)