Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the position of a UIBarButtonItem Programmatically

How would I be able to set the position of a UIBarButtonItem? Like, I would like to set it to be on either the very right of a UIToolbar or the very left depending on a state.

Thank you.

like image 877
Mark Avatar asked Nov 29 '22 18:11

Mark


2 Answers

You do not set directly the position of a UIBarButtonItem in an UIToolbar. Instead you defined the items' order and put flexible space on the left or on the right.

What you can do is:

  • Create the UIBarButtonItem you want to place (button 1).
  • Create an UIBarButtonItem of type UIBarButtonSystemItemFlexibleSpace (button 2).
  • If you want to put the button on the left, create an array with (button 1) and (button 2) and pass it to the UIToolbar by using the setItems:animated: method.
  • If you want to put the button on the right, create an array with (button 2) and (button 1) and pass it to the UIToolbar by using the setItems:animated: method.
like image 181
Laurent Etiemble Avatar answered Dec 07 '22 00:12

Laurent Etiemble


I hope it helps you...

UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
[keyboardDoneButtonView sizeToFit];

UIBarButtonItem* PrevButton = [[UIBarButtonItem alloc]  initWithBarButtonSystemItem:105 target:nil  action:nil]; //<
UIBarButtonItem*  NextButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:106  target:nil action:nil]; //>
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneClicked:)];

UIBarButtonItem* flexSpace = [[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *fake = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil] ;

[keyboardDoneButtonView setItems:[NSArray arrayWithObjects: PrevButton,fake, NextButton,fake,flexSpace,fake,doneButton,nil] animated:YES];

Link explains Bar Button Item Methods and Arguments https://developer.apple.com/library..... Use Fake Item to get exact pinch location on Button...

like image 33
Mohamed Jaleel Nazir Avatar answered Dec 07 '22 01:12

Mohamed Jaleel Nazir