2011-02-03 74 views
3

我有一個包含4個選項卡的應用程序。每個選項卡都是一個UINavigationController。 4個UINavigationBar標籤應該看起來相同,有一個自定義背景圖像,一個自定義backButton和一個自定義右鍵觸發一個函數。iPhone自定義UINavigationBar按鈕

我想在我的代碼中只做一次這些自定義,而不是在每個RootViewController中。

我設法將這個代碼到我的appDelegate有一個自定義背景圖片:

@implementation UINavigationBar (CustomImage) 
- (void)drawRect:(CGRect)rect { 
    UIImage *image = [UIImage imageNamed: @"MyNavigationBar.png"]; 
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
} 
@end 

,但我沒能定製後衛和右按鈕或指定右按鈕的動作。

有沒有辦法在appDelegate中做到這一點,就像背景圖片一樣?
或者我應該在每個RootViewController中進行自定義嗎?

回答

13

收件下面的代碼在viewWillAppear方法

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
UIImage *butImage = [[UIImage imageNamed:@"back.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:10]; 
[button setBackgroundImage:butImage forState:UIControlStateNormal]; 
[button addTarget:self action:@selector(gotoBack:) forControlEvents:UIControlEventTouchUpInside]; 
button.frame = CGRectMake(0, 0, 48, 30); 
UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease]; 
self.navigationItem.leftBarButtonItem = backButton; 

和寫入返回按鈕的動作事件。

-(IBAction)gotoBack:(id)sender 
{ 
    [self.navigationController popViewControllerAnimated:YES]; 
} 
+0

謝謝,但我必須寫在每個RootViewController的代碼(每個NavigationController )。我想要的是隻能爲所有NavigationControllers編寫一次代碼,就像我在appDelegate中爲類別創建背景圖像一樣。 – 2011-02-03 12:57:34

1

Renungas答案正常。

如果你不想寫同樣的代碼4次,你可以總是子類爲UINavigationController的 。

我只是試過這個解決方案(與UITabBarController的子類,但不過...) 它工作正常。

您可以搜索類似的例子here

您的自定義代碼(等同於提到的例子)應該是這樣的:

- (void)loadView { 

     [super loadView]; 

     UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [button setImage:[UIImage imageNamed:@"backbutton.png"] forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside]; 
     [button setFrame:CGRectMake(0, 0, 32, 32)]; 
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 

    } 

    - (void)backAction { 

     [self.navigationController popViewControllerAnimated:YES]; 
    } 

正如你可以看到所有你需要做的就是覆蓋的loadView並添加一個方法 來執行popVievController選擇器。

祝你好運!

3

在aplicationDidFinishLaunching您的appdelegate .....

UIImage *navBG = [UIImage imageNamed:@"barra-logo-centro.png"]; 

[[UINavigationBar appearance] setBackgroundImage:navBG forBarMetrics:UIBarMetricsDefault]; 

//backbutton: 22x30 , [email protected] 

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"back_button.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; 

[[UIBarButtonItem appearance] setBackgroundImage:[UIImage imageNamed:@"normal_button.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault]; 

這將改變整個導航欄proyect和欄按鈕項目