Ответ 1
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
Кто-нибудь успел создать информационную кнопку (курсив "i" в круге) в коде (читайте: без интерфейса Builder), а затем назначив ее как элемент правой кнопки панели навигации?
Я везде искал, и я даже не могу найти, как создать информационную кнопку в коде. Любая помощь будет принята с благодарностью.
UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
Вот довольно неплохое решение, которое, я думаю, охватывает все моменты, поднятые людьми в комментариях выше. Подобно принятому ответу, но этот подход включает дополнительный интервал (путем изменения кадра), чтобы кнопка не была разбита против правого края.
// Create the info button
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
// Adjust the frame by adding an addition 10 points to its width so the button is padded nicely
infoButton.frame = CGRectMake(infoButton.frame.origin.x, infoButton.frame.origin.y, infoButton.frame.size.width + 10.0, infoButton.frame.size.height);
// Hook the button up to an action
[infoButton addTarget:self action:@selector(showInfoScreen) forControlEvents:UIControlEventTouchUpInside];
// Add the button to the nav bar
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
// Also make sure to add a showInfoScreen method to your class!
Для Swift:
func addRightNavigationBarInfoButton() {
let button = UIButton(type: .infoDark)
button.addTarget(self, action: #selector(self.showInfoScreen), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
}
@objc func showInfoScreen() {
// info bar button pressed
}
Я думаю, это будет более полный ответ, и он должен помочь в любой ситуации:
-(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];
}