4

我在我的应用程序中使用 UINavigationController 及其栏。现在我想改变 leftBarButtonItem 和 rightBarButtonItem 的位置。我希望它们位于具有自定义宽度和高度的不同 x 和 y 位置。

但问题是,更改框架不会改变 barButtonItem 的任何内容。我现在不知道为什么,但框架总是被重置为其原始坐标。

这是我在 viewWillAppear 中调用的代码:

UINavigationItem *navItem = [[self.navigationBar items] lastObject];

UIView *rightview = [[UIView alloc] initWithFrame:CGRectMake(0,0,66,30)];
rightview.backgroundColor = [UIColor blueColor];

//add custom view
UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithCustomView:rightview];
navItem.leftBarButtonItem = search;

这是结果

视图不是从 0/0 开始,例如 x 位置在 0 的 5px insetead。

有关如何解决此问题的任何建议?

4

2 回答 2

12

这对我来说对 leftBarButtonItem 有用:如果您希望 UIBarButtonItem 精确显示在位置 (0, 0),您可以创建一个 UIButton,将其框架设置为 (-5, 0, width, height),假设偏移量为左 barbutton 项目是 (5, 0),并将其放置在您设置为 leftBarButtonItem 的 UIView 中。

#import "UINavigationItem+CSAButtons.h"

@implementation UINavigationItem (CSAButtons)


- (void) makeLeftBarButtonWithTarget:(id)target action:(SEL)action {

    UIImage * imageNormal = [UIImage imageNamed:@"normal.png"]; 
    UIImage * imageHighlighted = [UIImage imageNamed:@"highlighted.png"]; 
    UIImage * imageDisabled = [UIImage imageNamed:@"disabled.png"]; 

    // create your button
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.exclusiveTouch = YES;
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:imageNormal forState:UIControlStateNormal];
    [button setBackgroundImage:imageHighlighted forState:UIControlStateHighlighted];
    [button setBackgroundImage:imageDisabled forState:UIControlStateDisabled];

    // set the frame of the button (better to grab actual offset of leftbarbuttonitem instead of magic numbers)
    button.frame = CGRectMake(-5.0, 0.0, imageNormal.size.width, imageNormal.size.height);
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, imageNormal.size.width, imageNormal.size.height)];
    [view addSubview:button];

    // set the barbuttonitem to be the view
    UIBarButtonItem * barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.leftBarButtonItem = barButtonItem;
}
于 2013-04-27T21:37:21.100 回答
3

我不认为您有能力移动 aUIBarButtonItem但您可以通过将该UIView元素作为子视图添加到导航栏(或navItem)来实现相同的效果。你需要玩一点。它应该允许更大的灵活性。

希望这可以帮助。

于 2012-08-22T17:57:08.083 回答