Search code examples
iosuinavigationcontrollerheightuinavigationbartitleview

How to get the height of navigationBar's titleView?


I use a button as the titleView. But when I want to get the height of the button, whennever I use the self.button.frame.size.height or self.navigationItem.titleView.frame.size.height, it always return 0; Other value (like x, y and width) may seems reasonable.

Why?

In loadView
{
    self.switchButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [self.switchButton setTitle:@"TapMe" forState:UIControlStateNormal];
    self.navigationItem.titleView = self.switchButton;
    [self.switchButton addTarget:self action:@selector(doSomeThing:) forControlEvents:UIControlEventTouchUpInside];
 }

And

-(void)doSomeThing:(id)sender
{
    NSLog(@"height%f", self.switchButton.frame.size.height);
}

Solution

  • You can use

    First assign A view to TitleView

    UILabel *titiLbl = [[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)]autorelease];
    titiLbl.text = @"Title Name";
    self.navigationItem.titleView = titiLbl;
    

    Then to find the height of titleView

    CGRect navigationframe = self.navigationItem.titleView.frame;
    NSLog(@"navigationframe Height=%f",navigationframe.size.height);
    

    and please keep this in mind that if any view is not assigned to titleView of the NavigationItem It will return you 0.000;