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

Eri*_*isk 10 iphone frontend uinavigationbar uinavigationcontroller ios

我正在使用自定义导航栏构建应用程序.经过一些研究后,我决定使用UINavigationBar上的类别来做这件事.导航栏需要比平时稍大一点才能容纳投影.这是代码:

#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
Run Code Online (Sandbox Code Playgroud)

现在唯一的问题是较大的导航栏意味着导航栏按钮结束得太远,如下所示:

在此输入图像描述

有谁知道如何纠正按钮的位置?

谢谢大家的帮助!

更新:

我在视图控制器的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];
Run Code Online (Sandbox Code Playgroud)

ada*_*dam 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];
Run Code Online (Sandbox Code Playgroud)