以编程方式设置UIBarButtonItem的标识符

4

我在xib文件中有一个UIBarButtonItem项。我可以在xib文件中将其标识符设置为play、pause、page curl等。那么我该如何通过编程的方式实现这个功能呢?

4个回答

7

这应该可以在viewDidLoad中工作。

UIBarButtonItem *barButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:tar action:act] autorelease];
self.navigationItem.rightBarButton = barButtonItem;

其中,systemItem是你想要使用的UIBarButtonSystemItem类型。完整的选项列表在这里


3
重点是,你不能改变已经存在的一个,你必须创建一个新的。 - jrturton
@jrturton,我没有理解问题的那一部分,但是没错。如果需要,我猜你可以使用旧的目标和动作属性创建一个具有不同样式的新对象。 - wattson12

1

如果我理解正确,您想使用按钮在不同的系统图像之间切换?我曾经遇到过类似的情况,需要在EditDone之间切换。尽管这些是文本标签,但情况基本相同。

我唯一成功的方法是在viewDidLoad中创建两个单独的UIBarButtonItem实例,就像wattson12上面描述的那样,并在需要时将正确的实例分配给self.navigation.leftBarButton


0

我遇到了同样的问题,我阅读了wattson12的回答,然后我用另一种类似的方式解决了。我不知道哪种方法更有效。

//play button

@IBAction func startIt(sender: AnyObject) {

@IBAction func startIt(sender: AnyObject) {

    startThrough();

};

//播放按钮

func startThrough(){ timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true);

    let pauseButton = UIBarButtonItem(barButtonSystemItem: .Pause, target: self, action: "pauseIt");
    self.toolBarIt.items?.removeLast();
    self.toolBarIt.items?.append( pauseButton );

}

函数暂停() {

    timer.invalidate();

    let play = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: "startThrough");
    self.toolBarIt.items?.removeLast();
    self.toolBarIt.items?.append( play );

}

-3

如果您在 IB 中将标识符设置为“自定义”,那么至少可以更改标题:

 -(IBAction)editList:(UIBarButtonItem *)sender {
    edit=!edit;
    [imageListTable setEditing:edit animated:NO];
    if(edit){
      [sender setStyle:UIBarButtonItemStyleDone];
      [sender setTitle:@"Done"];
    }else{
      [sender setStyle:UIBarButtonItemStyleBordered];
      [sender setTitle:@"Edit"];
    }
 }

实际上,我发现在设备上运行时,以这种方式正确地工作:[self.tableView setEditing:!self.tableView.editing animated:YES]; if (!self.tableView.editing) { sender.style = UIBarButtonSystemItemDone; sender.title = @"编辑"; } else { sender.style = UIBarButtonSystemItemEdit; sender.title = @"完成"; } - simonthumper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接