在swift中添加UIBarButton项 [英] Adding UIBarButton item in swift

查看:83
本文介绍了在swift中添加UIBarButton项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将UIBarButton项添加到导航栏。

I'm trying to add a UIBarButton item to my nav bar.

这是我的导航栏类声明:

Here is my Navigation Bar class declaration:

import UIKit

class NavigationBarController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        configureToolbar()        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // #pragma mark - Navigation bar data source

    func configureToolbar() {
        let toolbarButtonItems = [
            searchBarButtonItem
        ]
        toolbar.setItems(toolbarButtonItems, animated: true)
    }

    var searchBarButtonItem: UIBarButtonItem {
        return UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:")
    }
}

没有错误在编译器中,但我得到的只是一个简单的导航栏。

No error in compiler, but all I get is a plain navigation bar.

如何显示UIBarButtonItem?

How do I get the UIBarButtonItem to show up?

推荐答案

将项目添加到 NavigationController NavigationBar NavigationBar 添加到 ViewController ,您需要先通过 NavigationItem 。试试这个:

To add items to the NavigationBar of a NavigationController, or a NavigationBar added to a ViewController, you will need to first go through NavigationItem. Try this:

self.navigationItem.setRightBarButtonItems(navigationBarButtonItemsArray, animated: true)

// Or if you just want to insert one item.

self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true)

要将按钮切换到左侧,只需将 setRightBarButtonItem 替换为 setLeftBarButtonItem setLeftBarButtonItems

To switch the button to the left side, just replace setRightBarButtonItem to setLeftBarButtonItem or setLeftBarButtonItems.

这篇关于在swift中添加UIBarButton项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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