Как добавить кнопку правого бара в панель навигации в iphone
Я хочу добавить элемент панели справа на панель навигации, чтобы при щелчке он выполнял определенную функцию.
Я создал следующий код, чтобы добавить элемент кнопки правой панели, но после этого элемент панели не отображается на панели навигации:
-(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];
}
Ответы
Ответ 1
-(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];
}
Попробуйте другие ответы. Я отправил этот ответ так, чтобы он работал, если ваш диспетчер просмотра не имеет контроллера навигации, который, по моему мнению, является проблемой.
Ответ 2
Предположим, у вас есть 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)];
Используйте свой собственный диспетчер представлений вместо навигационного контроллера для ссылки на navigationItem.
Ответ 3
Добавить этот код в viewdidload
UIBarButtonItem *chkmanuaaly = [[UIBarButtonItem alloc]initWithTitle:@"Calculate" style:UIBarButtonItemStylePlain target:self action:@selector(nextview)];
self.navigationItem.rightBarButtonItem=chkmanuaaly;
[chkmanuaaly release];
Ответ 4
В большинстве ответов здесь указывается настройка rightBarButtonItem UINavigationBar из нового VC после его отображения. Моя потребность, на которую фактически ответил Янош, заключается в том, чтобы установить элементы 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];
Теперь, предоставленный, это может показаться излишним ответом Яноса, но мне нужно больше очков повторения, чтобы о его ответе.; -)
Ответ 5
Я думаю, это будет более полный ответ, и он должен помочь в любой ситуации:
-(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];
}
Ответ 6
UIBarButtonItem *add=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addUser)];
self.navigationItem.rightBarButtonItem=add;
[add release];
Ответ 7
Используйте следующий код:
UIBarButtonItem *add=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addUser)];
self.navigationItem.rightBarButtonItem=add;
[add release];
Надеюсь, это поможет вам.
Наслаждайтесь!
Ответ 8
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];
}
Ответ 9
Swift:
let rightButton = UIBarButtonItem(image: UIImage(named: "imageName"),
style: .plain,
target: self,
action: #selector(buttonTapped))
navigationItem.setRightBarButton(rightButton, animated: false)
func settingsButtonTapped() {
// Implement action
}