2011-05-29 230 views
10

我正在用自定義導航欄構建應用程序。在做了一些研究後,我決定使用UINavigationBar上的一個類別來做這件事。導航欄需要比平時大一點才能容納投影。下面是代碼:iOS:在自定義導航欄中定位導航欄按鈕

#import "UINavigationBar+CustomWithShadow.h" 

@implementation UINavigationBar (CustomWithShadow) 

- (void)drawRect:(CGRect)rect { 

    // Change the tint color in order to change color of buttons 
    UIColor *color = [UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:0.0]; 
    self.tintColor = color; 

    // Add a custom background image to the navigation bar 
    UIImage *image = [UIImage imageNamed:@"NavBar.png"]; 
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, 60)]; 
} 

- (void)layoutSubviews { 

    self.frame = CGRectMake(0, 20, self.frame.size.width, 60); 
} 
@end 

唯一的問題是現在的更大的導航欄是指在導航欄按鈕落得太遠,就像這樣:

enter image description here

有誰知道我可以改正按鈕的位置?

感謝您的幫助!

更新:

我的按鈕添加到視圖控制器的init方法的導航欄,如下所示:

// Create "Add" button for the nav bar 
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] 
    initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
    target:self 
    action:@selector(createNewEntry:)]; 
[[self navigationItem] setRightBarButtonItem:addButton]; 
[addButton release]; 
+0

如何添加'UIBarButtonItem'到酒吧?哪裏?我做了一個小測試,在其中我通過NIB添加了btns,一切似乎都正常。 – 2011-05-29 18:43:54

+0

我將它們添加到視圖控制器的init方法中,例如使用[[self navigationItem] setRightBarButtonItem:addButton];'。我如何通過NIB添加按鈕? – 2011-05-29 19:01:28

回答

3

你需要的leftBarButtonItem和rightBarButtonItem添加自定義項目和與框架混亂....例如:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,5,buttonImage.size.width,buttonImage.size.height)]; 
[button setBackgroundImage:buttonImage forState:UIControlStateNormal]; 
[button addTarget:delegate action:@selector(barButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 
[button setTitle:titleString forState:UIControlStateNormal]; 
[button setTitleColor:CUSTOM_BAR_BUTTON_TITLE_COLOR forState:UIControlStateNormal]; 
[[button titleLabel] setFont:[UIFont boldSystemFontOfSize:14]]; 
[[button titleLabel] setShadowColor:CUSTOM_BAR_BUTTON_SHADOW_COLOR]; 
[[button titleLabel] setShadowOffset:CGSizeMake(0,-1)]; 

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button]; 
[button release]; 

[[self navigationItem] setRightBarButtonItem:barButton]; 
[barButton release]; 
+0

有沒有更簡單的方法?我在隨後的視圖中有按鈕,並且希望儘可能避免將它們中的每一個添加爲自定義項目。隨意建議替代品的方式,我添加陰影的方式,如果你有任何的導航欄:) – 2011-05-29 18:32:05

+0

@Erik你將不得不使用一個customView-bar-button-item以實際按鈕作爲子視圖來修復這種偏移的問題。 – Till 2011-05-29 19:41:45

+0

在所有導航按鈕上實現此操作的更簡單方法是創建UINavigationBarButton的子類或類別。 – adam 2011-05-30 14:08:29

0

嘗試將按鈕添加到導航欄中的而不是視圖控制器的方法。

+0

恐怕沒有變化。這些按鈕會繼續將其自身對齊到導航欄的底部(即下到陰影的末端)。 – 2011-05-29 19:44:54

0

我的解決方案,不是最好的,但它對我很好。我的自定義導航欄的高度爲55(默認高度爲44)。我從我的自定義導航欄中只剪切了44個高度並將其插入到導航欄中。然後我剪下自定義導航欄的下一部分(陰影等),並將其作爲圖像視圖插入到導航欄下。就是這樣。按鈕是在正確的地方...