Setting UIBarButtonItem identifier programmatically

I have a UIBarButtonItem element in an xib file. I can set its identifier as play, pause, page curl, etc. In the xib file. Now, how can I do this programmatically?

+4
source share
4 answers

this should work (in viewDidLoad)

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

where systemItem is the type of UIBarButtonSystemItem that you want to use. full list of options here

+7
source

If I understand correctly, do you want to switch between different system images using the button? I just had a similar case of switching between Edit and Done . Despite the fact that these are text labels, the situation is approximately the same.

The only thing I managed to do was create two separate instances of UIBarButtonItem in viewDidLoad in the manner described above, and assign the correct self.navigation.leftBarButton if necessary.

+1
source

I have the same problem, and I read wattson12 answer, then I solve another similar way. I do not know which is more efficient.

 //play button 

@IBAction func startIt (sender: AnyObject) {

  startThrough(); 

};

// play button

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

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

func pauseIt () {

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

If you set the "Custom" identifier to IB, you can at least change the title:

  -(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"]; } } 
-3
source

Source: https://habr.com/ru/post/1392713/


All Articles