自定义带navigationBar的自定义视图

参考官方文档,浅显提取和理解

参考链接

创建navigationBar

- (void)loadView{
    // view= nil会调用loadView方法
    // view为nil,在loadView内调用self.view会造成死循环,导致内存泄漏
    self.view = [[UIView alloc] init];
    
    _navigationBar = [[UINavigationBar alloc]init];
    _navigationBar.delegate = self;
    [self.view addSubview:_navigationBar];
}

计算statuBar到navigationBar的高度

CGFloat topLayoutGuide = 0.0f;
if ([self respondsToSelector:@selector(topLayoutGuide)])
   topLayoutGuide = (self.topLayoutGuide).length;

根据此设置navigationBar的frame

[_navigationBar sizeToFit]; // return 'best' size to fit current view bounds
_navigationBar.frame = CGRectMake(_navigationBar.frame.origin.x, topLayoutGuide,_navigationBar.frame.size.width,_navigationBar.frame.size.height);

计算剩余展示子视图或子控制器的frame

return CGRectMake(0,
_navigationBar.frame.size.height + _navigationBar.frame.origin.y,
self.view.bounds.size.width,
self.view.bounds.size.height - _navigationBar.frame.size.height - _navigationBar.frame.origin.y);

你可能感兴趣的:(自定义带navigationBar的自定义视图)