2012-05-28 70 views
1

這是默認情況下xcode的功能:當您在導航控制器中查看第一個視圖時,「返回」按鈕不會出現在標題中。後退按鈕僅在您前往另一個由第一個視圖實例化的視圖時纔會出現。iphone應用程序 - 爲NavigationController創建一個主頁按鈕?

我想要一個主頁按鈕或後退按鈕以便在第一個視圖中出現。點擊它會執行一個特定的操作....就像說改變rootviewcontroller。我怎樣才能讓這個按鈕出現,以及如何僅在第一個視圖中覆蓋它的行爲?在任何其他視圖中,後退按鈕的行爲應該作爲默認行爲。

回答

0

在你的根視圖控制器的viewDidLoad方法,初始化一個UIBarButtonItem並將其添加到導航控制器的工具欄:

UIBarButtonItem *homeButton = [[UIBarButtonItem alloc] 
           initWithTitle:@"Home" 
           target:[AppDelegate sharedDelegate] 
           action:@selector(changeRootViewController)]; 
[self.navigationItem setLeftBarButton:homeButton animated:NO]; 

target應該是你的應用程序委託類,如果你想換出根視圖控制器。在該類中創建一個名爲changeRootViewController的方法來執行視圖控制器交換。

您可以使用initWithImage:更改homeButton以使用圖像而不是文字。

0

試試這個:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
NSString* backBtnImg = @"myImage"; 
UIImage *buttonImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:backBtnImg ofType:@"png"]]; 
[button setBackgroundImage:buttonImage forState:UIControlStateNormal]; 
[button setTitle:@"back" forState:UIControlStateNormal]; 
[button addTarget:self action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside]; 
[button setFrame:CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height)]; 

UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 
self.navigationItem.leftBarButtonItem = btnItem;