2010-02-27 27 views
1

我想要用自定義控件實現UINavigationBar。所以,我已經添加的UIView上UINavigationBar的左側,並試圖將控件添加到UIView的與下面的代碼:自定義查看UINavigationBar左邊的按鈕

UIView *view = navigationController.navigationItem.leftBarButtonItem.customView; 
UIButton *button = [[UIButton alloc] initWithFrame:view.frame]; 
[button setTitle:@"TEST" forState:UIControlStateNormal]; 
[view addSubview:button]; 
[button sizeToFit]; 
[button release]; 

代碼的工作,但按鈕不會出現。

任何幫助,將不勝感激。 謝謝。

UPD

OK,我給一個嘗試下面的代碼,並做了這樣的事情:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 50)]; 
[button setTitle:@"XXX" forState:UIControlStateNormal]; 
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 
navigationController.visibleViewController.navigationItem.leftBarButtonItem = customItem; 
[customItem release]; 
[button release]; 

的 「XXX」 的稱號確實出現,但它看起來像簡單的標籤,而不是按鈕。有任何想法嗎?

回答

4

是的,你的UIButton不附帶任何陰影。我所做的是使用一個UISegmentedControl獲得陰影免費:

// Add the Menu button to the navigation bar 
NSString* menuLabel = "ShadeButton"; 
CGSize textSize = [menuLabel sizeWithFont:[UIFont systemFontOfSize:15.0]]; 
UISegmentedControl* menuSegmentedButton = [[UISegmentedControl alloc] 
    initWithFrame:CGRectMake(0.0f, 0.0f, textSize.width, 29.0f)]; 
menuSegmentedButton.momentary = YES; 
menuSegmentedButton.selected = NO; 
menuSegmentedButton.segmentedControlStyle = UISegmentedControlStyleBar; 
[menuSegmentedButton insertSegmentWithTitle:menuLabel atIndex:0 
           animated:NO]; 
[menuSegmentedButton addTarget:self action:@selector(doMenu) 
     forControlEvents:UIControlEventValueChanged]; 
UIBarButtonItem* barButton = [[UIBarButtonItem alloc] 
    initWithCustomView:menuSegmentedButton]; 
[menuSegmentedButton release]; 
self.navigationItem.rightBarButtonItem = barButton; 

與UISegmentedControl創建您的UIBarButtonItem如上圖所示,而不是一個UIButton,你應該得到你之後的效果。另一種方法是在按鈕上做更多的工作,併爲它自己創建一個紋理/自定義圖像。

+0

好的,我會在最近一週內嘗試一下,如果它有效 - 我會給你那個賞金:) –

+0

按鈕的外觀似乎不同於標準樣式,但它對我來說並不重要 - 它應該被剝皮。謝謝你的幫助。 –

3

注意很對。

如果你只是想要一個不同的標題:

UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithTitle:@"TEST" style:UIBarButtonItemStylePlain target:nil action:nil]; 
navigationController.navigationItem.leftBarButtonItem = customItem; 
[customItem release]; 

如果你真的想要一個自定義視圖:

// Create Custom View called myView. 
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:myView]; 
navigationController.navigationItem.leftBarButtonItem = customItem; 
[customItem release]; 
相關問題