0

viewDidLoad我有下列方式實現了自定義背景UINavigationBar的:奇怪的行爲被按下

[self.navigationController.navigationBar insertSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:nav_bg_image]] atIndex:100]; 

在堆棧的頂部(稱之爲RVC)我有以下完整的代碼:

UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:navbar_image_logo]]; 
[self.navigationController.navigationBar insertSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:nav_bg_image]] atIndex:100]; 
[self.navigationItem setTitleView:logoView]; 
[logoView release]; 

這工作出色。然而,當我在堆棧上推送新VCviewDidLoad

UIImageView *logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:navbar_image_logo]]; 
[self.navigationController.navigationBar insertSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:nav_bg_image]] atIndex:1]; 
[self.navigationItem setTitleView:logoView]; 
[logoView release]; 
UIBarButtonItem *hButton = [[UIBarButtonItem alloc] initWithTitle:@"Filters" style:UIBarButtonItemStylePlain target:self action:@selector(filtersAction)]; 
self.navigationItem.rightBarButtonItem = hButton; 
[hButton release]; 

使用相同的代碼出現無論是「過濾器」按鈕,也沒有titleview的ImageView的。但是,我知道過濾器按鈕已添加到用戶界面,因爲如果我點擊它應該出現的區域,則會執行操作。

此外,當我深入查看詳細視圖DVC並返回時,突然出現titleView(logoView)!

我懷疑這是某種內存問題,但我一直無法解決它。

回答

2

有你在IDEV食譜How do iPhone apps Instagram/Reeder/DailyBooth implement custom NavigationBars with variable width back buttons?

基本上你是加入你在錯誤的道路背景訂貨遇到的問題的提及。

只支持iOS 5的
實現諸如setBackgroundImage:forBarMetrics:

支持舊的iOS的+ iOS 5的

  1. 子類UINavigationBar的方法和實施drawRect

    //.h 
    @interface CustomNavigationBar : UINavigationBar 
    @end 
    
    //.m 
    @implementation CustomNavigationBar 
    
    - (void)drawRect:(CGRect)rect; 
    { 
        UIImage *image = [[UIImage imageNamed: @"BackgroundImage"] stretchableImageWithLeftCapWidth:0 topCapHeight:0]; 
        [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; 
    } 
    
    @end 
    
  2. 要獲得UINavigationController以使用您的子類,您需要使用xib創建它。

enter image description here


如果您在代碼中設置好一切,你仍然需要使用筆尖來做到這一點。 我用筆尖沒有File's Owner,只包含一個Navigation Controller被配置爲使用我CustomNavigationBar,並沒有viewControllers

在這種情況下,我在代碼中設置這件事是這樣的:

// Load my nib with only a Navigation Controller and custom navigationBar 
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomNavigationController" owner:nil options:nil]; 

// The only top level object will be my navigationController 
UINavigationController *navigationController = [topLevelObjects objectAtIndex:0]; 

// Push a view controller to be the rootViewController 
[navigationController pushViewController:rootViewController animated:NO]; 

然後呈現這個控制器,但我通常會。顯示它的控制器/窗口將採取所需的保留在UINavigationController

+0

感謝您提供非常豐富的答案! –

1

您使用方法insertSubView:atIndex:看起來很可疑。該視圖中真的有100個子視圖嗎?

+0

不,最初我在索引爲0時,但我想(爲了調試目的)確保它沒有取代另一個視圖,因爲它佔用整個視圖。 - 它不適用於索引:0,1或100. –

+0

只能在有效索引處插入。如果您希望添加的子視圖出現在「前面」,只需使用「-addSubview:」(即索引參數與zIndex相同) – nielsbot