iOS:在自定义导航栏中定位导航栏button
我正在build立一个自定义导航栏的应用程序。 经过一番研究,我决定在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
现在唯一的问题是,较大的导航栏意味着导航栏button结束了太多,如下所示:
有谁知道我可以如何纠正button的位置?
感谢所有的帮助!
更新:
我在视图控制器的init方法中将button添加到导航栏中,如下所示:
// Create "Add" button for the nav bar UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(createNewEntry:)]; [[self navigationItem] setRightBarButtonItem:addButton]; [addButton release];
您将需要添加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];
尝试将视图控制器的viewDidLoad
方法中的button添加到导航栏中。
我的解决scheme,不是最好的,但它对我很好。 我的自定义导航栏的高度为55(默认高度为44)。 我从我的自定义导航栏中只剪切了44个高度,并将其插入到导航栏中。 然后我剪下我的自定义导航栏的下一部分(阴影等),并将其作为图像视图在导航栏下方插入。 就是这样。 button在正确的地方…