1

我需要更改导航栏的高度并在左上角添加自定义图像按钮。我在那里的一部分,但现在失去了将自定义图像按钮放在正确的位置。这是我所拥有的:

为了调整高度,我使用一种方法创建了 UINavBar 类别,如下所示:@implementation UINavigationBar (myNavBar)

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize newSize = CGSizeMake(768,80);
    return newSize;
}

@end

我还创建了一个 UINavigationController 子类来修改按钮。这是该类的 viewDidLoad:

UIImage *navBackgroundImage = [UIImage imageNamed:@"bar"];
[[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];


// Change the appearance of back button
UIImage *backButtonImage = [[UIImage imageNamed:@"back_off"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 13, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

// Change the appearance of other navigation button
UIImage *barButtonImage = [[UIImage imageNamed:@"menu_off"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 6, 0, 6)];
[[UIBarButtonItem appearance] setBackgroundImage:barButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

到目前为止,此解决方案调整了顶部导航栏的大小,但将我的按钮定位在一个奇怪的位置。这是我想要的与正在发生的事情:

我想要的是

目标

我得到了什么

实际的

4

1 回答 1

1

我有一个 UIBarButtonItem 类别,我使用它有一个偏移属性:

UIBarButtonItem+CustomImage.h

@interface UIBarButtonItem (CustomImage)

+ (UIBarButtonItem*)barItemWithImage:(UIImage*)image target:(id)target action:(SEL)action offset:(CGPoint)offset;

@end

UIBarButtonItem+CustomImage.m

#import "UIBarButtonItem+CustomImage.h"

@implementation UIBarButtonItem (CustomImage)

+ (UIBarButtonItem *)barItemWithImage:(UIImage *)image target:(id)target action:(SEL)action offset:(CGPoint)offset {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0.0, 0.0, image.size.width, image.size.height)];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBounds:CGRectOffset(button.bounds, 0.0, -10.0)];

    UIView *container = [[UIView alloc] initWithFrame:button.frame];
    [container setBounds:CGRectOffset(container.bounds, offset.x, offset.y)];
    [container addSubview:button];

    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:container];
    return item;
}

@end

示例用法

#import "UIBarButtonItem+CustomImage.h"

UIBarButtonItem *settingsButton = [UIBarButtonItem barItemWithImage:settingsImage
                                                 target:self
                                                 action:@selector(revealSettings:)
                                                 offset:CGPointMake(0.0, 0.0)];

[self.navigationItem setLeftBarButtonItem:settingsButton];
于 2013-11-19T20:06:58.277 回答