問題: 妹子最近在寫代碼的時候想使用一下UIViewController自帶的navigationVIewController的時候發現無論在navigation中寫入什么代碼,界面都沒有顯示,通過分層圖發現界面上壓根就沒有這個navigationBar的容器啊,哪里去了,哪里去了?
例子:先貼出妹子錯誤的示范:
if (self.navigationController) { // 去掉這一層也是錯誤的示范哦
self.navigationItem.title = @"姨嗎愛買";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(selector)];
}
原因:查閱了navigationController的屬性,發現沒有在本界面設置某一個屬性就可以使得navigationBar出來,而問題的根本在這里
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = navigationController;
只有在APPdelegate中添加了這句話,並且保證self.window.rootViewController = navigationController;才會創建出navigationBar;
所以如果是簡單的demo的話是可以直接這樣使用的,但是一個復雜的demo中是需要用到各種視圖控制器,比如tabBar這樣兩者就會發生沖突,面對這種情況下,小伙伴們要乖乖的自定義一個navigationViewController,添加到UITableView中,然后自定義這個navigationViewController,代碼如下
例如:
@property (nonatomic, strong) UIView *tableHeaderView;
- (UITableView *)tableView
{
if (!_tableView) {
_tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
_tableView.tableHeaderView = self.tableHeaderView;
}
return _tableView;
}
- (UIView *)tableHeaderView
{
if (!_tableHeaderView) {
_tableHeaderView = [[UIView alloc]init];
_tableHeaderView.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 100);
_tableHeaderView.backgroundColor = [UIColor clearColor];
}
return _tableHeaderView;
}
雖然寫完以后覺得很簡單,但是之前一直找不到原因啊,所以記錄下來希望能幫到需要的小伙伴