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

时间:2015-06-08 10:03:36

标签: ios swift programmatically-created

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

3 个答案:

答案 0 :(得分:6)

带图片:

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)

用于在按钮之间有相似的空间。

答案 1 :(得分:1)

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;

答案 2 :(得分:0)

试试这段代码 -

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