如何以编程方式将 UIBarButtonItem 添加到我的导航控制器?

How can I add UIBarButtonItem to my navigation controller programmatically?

我想在左侧和右侧以编程方式将 UIBarButtonItem 添加到我的导航控制器,并在单击时将它们都更改为其他 UIBarButtonItems。而且我还想使用我的项目图标。我可以这样做吗?这是我在 iOS 编程的第二周 如果它是一个简单的问题,请原谅

配图:

self.navigationItem.setLeftBarButtonItem( (UIBarButtonItem(image:UIImage(named:"image"), style: .Plain, target:self, action:"action:")), animated: false)

标题为:

self.navigationItem.setLeftBarButtonItem( (UIBarButtonItem(title:"backButton", style: .Plain, target:self, action:"back_pressed:")), animated: false)

此外,您可以为每一面分配多个项目:

var test: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"test"), style: UIBarButtonItemStyle.Plain, target: self, action: "test1:")
var test2: UIBarButtonItem = UIBarButtonItem(image: UIImage(named:"test2"), style: UIBarButtonItemStyle.Plain, target: self, action: "test2:")
navigationItem.rightBarButtonItems = [test1, test2]

使用多个项目时您可能感兴趣:

var spacing : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)

用于在按钮之间有类似的space。

试试这个代码-

self.title = "Title"

var left : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

var right : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

self.navigationItem.leftBarButtonItem = left
self.navigationItem.rightBarButtonItem = right

Objective-C 版本

    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"close"] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = closeButton;

    //OR

    UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = closeButton;