iOS:在自定义导航栏中定位导航栏按钮

iOS:在自定义导航栏中定位导航栏按钮

问题描述:

我正在用自定义导航栏构建应用程序。在做了一些研究后,我决定使用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

你需要的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

恐怕没有变化。这些按钮会继续将其自身对齐到导航栏的底部(即下到阴影的末端)。 – 2011-05-29 19:44:54

我的解决方案,不是最好的,但它对我很好。我的自定义导航栏的高度为55(默认高度为44)。我从我的自定义导航栏中只剪切了44个高度并将其插入到导航栏中。然后我剪下自定义导航栏的下一部分(阴影等),并将其作为图像视图插入到导航栏下。就是这样。按钮是在正确的地方...