Как добавить правую кнопку на панели навигации в iPhone
-
27-10-2019 - |
Вопрос
Я хочу добавить правую кнопку кнопки в панель навигации, так что при щелчке он выполняет определенную функцию.
Я создал следующий код, чтобы добавить правильный элемент кнопки, но после того, как это сделано, элемент кнопки штрих не отображается в панели навигации:
-(void)viewDidload{
self.navigationItem.rightBarButtonItem =
[[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(Add:)] autorelease];
}
-(IBAction)Add:(id)sender
{
TAddNewJourney *j=[[TAddNewJourney alloc]init];
[app.navigationController pushViewController:j animated:YES];
[j release];
}
Решение
-(void)viewDidLoad
{
[super viewDidLoad];
app.navigationController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(Add:)] autorelease];
}
-(IBAction)Add:(id)sender
{
TAddNewJourney *j=[[TAddNewJourney alloc]init];
[app.navigationController pushViewController:j animated:YES];
[j release];
}
Попробуйте другие ответы. Я опубликовал этот ответ, чтобы он сработал, если у вашего ViewController нет контроллера навигации, который, я думаю, является проблемой.
Другие советы
Предположим, у вас есть Uiviewcontroller, например:
UIViewController *vc = [UIViewController new];
И вы добавили его в контроллер навигации:
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
Таким образом, rightbarbuttonitem будет Не отображается:
nc.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"xyz" style:UIBarButtonItemStyleDone target:self action:@selector(xyz)];
Но так это появится:
vc.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"xyz" style:UIBarButtonItemStyleDone target:self action:@selector(xyz)];
Используйте свой собственный ViewController вместо NavigationController для ссылки на NavigationItem.
Добавьте этот код в ViewDidload
UIBarButtonItem *chkmanuaaly = [[UIBarButtonItem alloc]initWithTitle:@"Calculate" style:UIBarButtonItemStylePlain target:self action:@selector(nextview)];
self.navigationItem.rightBarButtonItem=chkmanuaaly;
[chkmanuaaly release];
Большинство ответов здесь адреса устанавливает право uinavigationbar RightbarbarbuttonItem из нового венчурного капитала после того, как он будет показан. Моей потребности, на которую на самом деле ответил Янос, состоит в том, чтобы установить элементы UinavigationItem из Calling UiviewController. Следовательно, следующий код (спасибо, Янос).
// Изнутри себя (он же контроллер вызова):
UIViewController *c = [[[UIViewController alloc] init...] autorelease];
c.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissModalViewControllerAnimated:)] autorelease];
c.navigationItem.title = @"Title Goes Here";
UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:c] autorelease];
nav.navigationBarHidden = FALSE;
[self presentModalViewController:nav animated:YES];
Теперь, предоставленное, это может показаться излишним для ответа Яноса, но мне нужно больше очков повторения, чтобы отметить его ответ. ;-)
Я думаю, это будет более полным ответом, и это должно помочь в любой ситуации:
-(void)viewDidLoad{
//Set Navigation Bar
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
//Set title if needed
UINavigationItem * navTitle = [[UINavigationItem alloc] init];
navTitle.title = @"Title";
//Here you create info button and customize it
UIButton * tempButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
//Add selector to info button
[tempButton addTarget:self action:@selector(infoButtonClicked) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem * infoButton = [[UIBarButtonItem alloc] initWithCustomView:tempButton];
//In this case your button will be on the right side
navTitle.rightBarButtonItem = infoButton;
//Add NavigationBar on main view
navBar.items = @[navTitle];
[self.view addSubview:navBar];
}
UIBarButtonItem *add=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addUser)];
self.navigationItem.rightBarButtonItem=add;
[add release];
Используйте следующий код:
UIBarButtonItem *add=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addUser)];
self.navigationItem.rightBarButtonItem=add;
[add release];
Надеюсь, что это помогает вам.
Наслаждаться!
UIButton *dButton=[UIButton buttonWithType:0];
dButton.frame=CGRectMake(50,50,50,50);
[dButton addTarget:self action:@selector(clickdButton:)
forControlEvents:UIControlEventTouchUpInside];
[dButton setImage:[UIImage imageNamed:@"iconnavbar.png"]
forState:UIControlStateNormal];
dButton.adjustsImageWhenHighlighted=NO;
dButton.adjustsImageWhenDisabled=NO;
dButton.tag=0;
dButton.backgroundColor=[UIColor clearColor];
UIBarButtonItem *RightButton=[[[UIBarButtonItem alloc] initWithCustomView:dButton]autorelease];
self.navigationItem.rightBarButtonItem=RightButton;
а потом:
-(IBAction)clickdButton:(id)sender{
classexample *tempController=[[classexample alloc] init];
[self.navigationController pushViewController:tempController animated:YES];
[tempController autorelease];
}
Быстрый:
let rightButton = UIBarButtonItem(image: UIImage(named: "imageName"),
style: .plain,
target: self,
action: #selector(buttonTapped))
navigationItem.setRightBarButton(rightButton, animated: false)
func settingsButtonTapped() {
// Implement action
}