1

我使用一個按鈕作爲titleView。但是,當我想要獲得按鈕的高度時,無論何時使用self.button.frame.size.heightself.navigationItem.titleView.frame.size.height,它總是返回0;其他值(如x,y和寬度)似乎是合理的。如何獲取navigationBar的titleView的高度?

爲什麼?

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]; 
} 

而且

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

回答

0

您可以使用

首先分配以titleview的

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

然後找到titleview的

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

,並請保留這在米ind如果任何視圖未分配給NavigationItem的titleView它將返回0.000;

+0

多數民衆贊成恢復而不只是titleview的 –

+0

的一個整條的高度,我做了一個編輯我的答案 – spider1983

+0

我看到,我觀察到了一些情況。 'autorelease'不能與ARC應用程序一起使用(這是iOS5以來的默認設置,所以我想他正在使用它)。另外他使用的不是UILabel的UIButton。即使它可能沒有那麼大的改變,但精確度會更好。 –

0
self.navigationItems.navagationBar 

似乎並不正確。

什麼

CGRectGetHeight(self.navigationItem.titleView.frame) 
+0

對不起,我只是犯了一個錯誤。我的意思是,當我使用self.navigationItem.titleView.frame,otherthing還行,但高度始終爲零 – NewXcoder