Как добавить правую кнопку в UINavigationController?
Я пытаюсь добавить кнопку обновления в верхнюю панель навигационного контроллера без успеха.
Вот заголовок:
@interface PropertyViewController : UINavigationController {
}
Вот как я пытаюсь добавить его:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain
target:self action:@selector(refreshPropertyList:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
return self;
}
Ответы
Ответ 1
Попробуйте сделать это в viewDidLoad. Как правило, вы должны отложить все, что можете, до этого момента, когда UIViewController будет запущен, все еще может быть довольно долго, пока он не появится, не нужно начинать работу раньше и связывать память.
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(refreshPropertyList:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];
}
Что касается того, почему он не работает в настоящее время, я не могу сказать со 100% уверенностью, не видя больше кода, но происходит много вещей между init и загрузкой представления, и вы можете делать что-то, что вызывает navigationItem до reset.
Ответ 2
Попробуйте добавить кнопку к элементу navigationItem контроллера вида, который будет помещен в этот класс PropertyViewController
, который вы создали.
То есть:
MainViewController *vc = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];
PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];
Теперь этот информационный байт, который был создан программно, появится на панели навигации. Идея состоит в том, что навигационный контроллер берет свою отображаемую информацию (название, кнопки и т.д.) Из UIViewController
, которую он собирается отобразить. Вы фактически не добавляете кнопки и т.д. Непосредственно в UINavigationController
.
Ответ 3
Кажется, что некоторые люди (например, я) могут приехать сюда, чтобы узнать, как добавить кнопку панели навигации в Interface Builder. Ответ ниже показывает, как это сделать.
Добавить контроллер навигации на ваш раскадровки
Выберите свой контроллер просмотра, а затем в меню Xcode выберите Редактоp > Вставить в > Контроллер навигации.
![введите описание изображения здесь]()
В качестве альтернативы вы можете добавить UINavigationBar
из библиотеки объектов.
Добавить элемент кнопки панели
Перетащите UIBarButtonItem
из библиотеки объектов в верхнюю панель навигации.
![введите описание изображения здесь]()
Он должен выглядеть так:
![введите описание изображения здесь]()
Установить атрибуты
Вы можете дважды щелкнуть "Item", чтобы изменить текст на "Refresh", но есть реальный значок Refresh, который вы можете использовать. Просто выберите Инспектор атрибутов для UIBarButtonItem
и Элемент системы выберите Обновить.
![введите описание изображения здесь]()
Это даст вам значок Refresh по умолчанию.
![введите описание изображения здесь]()
Добавить действие IB
Управляйте перетаскиванием из UIBarButtonItem
в контроллер просмотра, чтобы добавить @IBAction
.
class ViewController: UIViewController {
@IBAction func refreshBarButtonItemTap(sender: UIBarButtonItem) {
print("How refreshing!")
}
}
Что это.
Ответ 4
Для "Обновить" есть системная кнопка по умолчанию:
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:@selector(refreshClicked:)] autorelease];
self.navigationItem.rightBarButtonItem = refreshButton;
}
- (IBAction)refreshClicked:(id)sender {
}
Ответ 5
Вы можете использовать это:
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(method:)];
self.navigationItem.rightBarButtonItem = anotherButton;
Ответ 6
-(void) viewWillAppear:(BOOL)animated
{
UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
[btnRight setFrame:CGRectMake(0, 0, 30, 44)];
[btnRight setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
[btnRight addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
[barBtnRight setTintColor:[UIColor whiteColor]];
[[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];
}
Ответ 7
Вот решение в Swift (при необходимости задайте параметры):
var optionButton = UIBarButtonItem()
optionButton.title = "Settings"
//optionButton.action = something (put your action here)
self.navigationItem.rightBarButtonItem = optionButton
Ответ 8
Для быстрого 2:
self.title = "Your Title"
var homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))
var logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))
self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton
Ответ 9
Почему вы подклассы UINavigationController
? Нет необходимости подклассифицировать его, если все, что вам нужно сделать, это добавить к нему кнопку.
Настройте иерархию с UINavigationController
вверху, а затем в корневом представлении контроллера viewDidLoad:
: настройте кнопку и прикрепите ее к элементу навигации, вызвав
[[self navigationItem] setRightBarButtonItem:myBarButtonItem];
Ответ 10
Вы можете использовать
self.navigationBar.topItem.rightBarButtonItem = otherButton;
Ответ 11
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];
view.backgroundColor = [UIColor clearColor];
UIButton *settingsButton = [UIButton buttonWithType:UIButtonTypeCustom];
[settingsButton setImage:[UIImage imageNamed:@"settings_icon_png.png"] forState:UIControlStateNormal];
[settingsButton addTarget:self action:@selector(logOutClicked) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setFrame:CGRectMake(40,5,32,32)];
[view addSubview:settingsButton];
UIButton *filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
[filterButton setImage:[UIImage imageNamed:@"filter.png"] forState:UIControlStateNormal];
[filterButton addTarget:self action:@selector(openActionSheet) forControlEvents:UIControlEventTouchUpInside];
[filterButton setFrame:CGRectMake(80,5,32,32)];
[view addSubview:filterButton];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
Ответ 12
Попробуйте это. Он работает для меня.
Панель навигации, а также добавлено фоновое изображение на правую кнопку.
UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage
imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
self.navigationItem.rightBarButtonItem=Savebtn;
Ответ 13
Используйте этот код для навигационной панели правой кнопки с выигранным названием и вызовите метод после нажатия правой кнопки.
UIBarButtonItem *btnSort=[[UIBarButtonItem alloc]initWithTitle:@"right" style:UIBarButtonItemStylePlain target:self action:@selector(sortedDataCalled)];
self.navigationItem.rightBarButtonItem=btnSort;
}
-(void)sortedDataCalled {
NSLog(@"callBtn");
}
Ответ 14
UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;
Ответ 15
- (void)viewWillAppear:(BOOL)animated
{
[self setDetailViewNavigationBar];
}
-(void)setDetailViewNavigationBar
{
self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
[self setNavigationBarRightButton];
[self setNavigationBarBackButton];
}
-(void)setNavigationBarBackButton// using custom button
{
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@" Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];
self.navigationItem.leftBarButtonItem = leftButton;
}
- (void)onClickLeftButton:(id)sender
{
NSLog(@"onClickLeftButton");
}
-(void)setNavigationBarRightButton
{
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
- (void)onClickrighttButton:(id)sender
{
NSLog(@"onClickrighttButton");
}
Ответ 16
self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshData)];
}
-(void)refreshData{
progressHud= [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
[progressHud setLabelText:@"拼命加载中..."];
[self loadNetwork];
}
Ответ 17
Вы должны добавить свой barButtonItem в метод - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
.
Ответ 18
Просто скопируйте и вставьте этот Objective-C код.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
[btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
self.navigationItem.rightBarButtonItem = barButton;
}
#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}
Ответ 19
@Artilheiro: Если это проект, основанный на навигации, вы можете создать BaseViewController. Все остальные представления наследуют этот BaseView. В BaseView u можно определить общие методы для добавления правой кнопки или для изменения текста левой кнопки.
Пример:
@interface BaseController: UIViewController {
} - (void) setBackButtonCaption: (NSString *) подпись;
(void) setRightButtonCaption: (NSString *) selectot: (SEL) селектор;
@end // В BaseView.M
(void) setBackButtonCaption: (NSString *) подпись {
UIBarButtonItem *backButton =[[UIBarButtonItem alloc] init];
backButton.title= caption;
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
} - (void) setRightButtonCaption: (NSString *) selecttion: (SEL) селектор {
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
rightButton.title = caption;
rightButton.target= self;
[rightButton setAction:selector];
self.navigationItem.rightBarButtonItem= rightButton;
[rightButton release];
}
И теперь в любом пользовательском представлении реализуйте это базовое представление с помощью методов:
@interface LoginView: BaseController {
В некотором методе метода метода вызова как:
SEL sel = @selector (switchToForgotPIN);
[super setRightButtonCaption: @ "Забыли PIN-код" selectot: sel];