Добавление UINavigationBar в UIView программно?
Я пытаюсь добавить UINavigationBar в UIView программно и с таким успехом, и не могу понять это. Я пытаюсь добавить его в свой подкласс UIView, и он просто не появляется, когда я запускаю свое приложение.
Вот мой код:
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, headerHeight)];
[navBar setBackgroundColor:[UIColor blueColor]];
[self addSubview:navBar];
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"done" style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"categories"];
[navItem setRightBarButtonItem:doneItem animated:YES];
[navBar setItems:[NSArray arrayWithObject:navItem] animated:YES];
Ответы
Ответ 1
Если вы используете контроллер навигации с первого взгляда, я предлагаю это в вашем Appdelegate.m.
UIViewController *viewController = [[MenuViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController=navController;
но если у вас есть представление, представляющее ваше новое представление, которое вы хотите, чтобы navbar использовал это для отображения нового представления:
UIViewController *viewController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self presentViewController:navigationcontroller animated:YES completion:nil];
то вы можете добавить свои navBarButtons во второе представление, как показано ниже:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(btnAddGroupPressed)];
self.navigationItem.rightBarButtonItem=btnAdd;
}
return self;
}
Ответ 2
Я не уверен, что происходит. Вот код, который я использую, чтобы воспроизвести вашу проблему:
Файл *.h пуст
#import "STTestView.h"
@implementation STTestView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
navBar.barTintColor = [UIColor purpleColor];
[self addSubview:navBar];
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"done" style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"categories"];
[navItem setRightBarButtonItem:doneItem animated:YES];
[navBar setItems:[NSArray arrayWithObject:navItem] animated:YES];
self.backgroundColor = [UIColor darkGrayColor];
}
return self;
}
-(void)done:(id)sender {
}
@end
И вот что я получаю:
![enter image description here]()
Вы можете:
- Добавить код для всего метода
initWithFrame:
?
- Убедитесь, что self.frame и headerHeight на самом деле правильно установлены к моменту запуска вашего кода?
- Не забудьте использовать свойство
backgroundColor
, но свойство barTintColor
Надеюсь, это поможет!
Ответ 3
Я не могу сказать вам, почему, но я испытал эту же проблему, и я проследил ее до метода setBackgroundColor
. Чтобы обойти это, я сделал:
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44.0)];
UINavigationItem *titleItem = [[UINavigationItem alloc] initWithTitle:@"MyNavBar"];
NSDictionary *titleAttributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor],
UITextAttributeTextColor,
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0],
UITextAttributeTextShadowColor,
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
UITextAttributeTextShadowOffset,
[UIFont fontWithName:@"HelveticaNeue-Light" size:20.0],
UITextAttributeFont,
nil];
navBar.titleTextAttributes = titleAttributesDictionary;
navBar.items = @[titleItem];
navBar.tintColor=[UIColor blueColor];
[self addSubview:navBar];
Ответ 4
Возможно, вы забыли "navBar.items = @[navItem];" поскольку я имел дело с аналогичной проблемой:
UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, headerHeight)];
navBar.barTintColor = [UIColor blueColor];
[self addSubview:navBar];//it is important point, otherwise, you can see only the area without any item
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"done" style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
[navItem setRightBarButtonItem:doneItem animated:YES];
[navBar setItems:[NSArray arrayWithObject:navItem] animated:YES];
Используйте эти свойства: "barTintColor", чтобы получить цвет фона панели навигации, и "tintColor" для элементов навигации и элементов панели.
Ответ 5
Если вы используете xib вместо раскадровки, тогда пишите эти строки в AppDelegate:
UIViewController *viewControllerObj = [[MenuViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewControllerObj];
self.window.rootViewController=navController;
Если вы используете раскадровку, тогда полезно добавить NavigationController из меню.