【问题标题】:UINavigationBar - change UIBarButtonItem positionsUINavigationBar - 改变 UIBarButtonItem 的位置
【发布时间】:2013-04-28 05:37:21
【问题描述】:

我在我的应用程序中使用 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 处。

关于如何解决这个问题的任何建议?

【问题讨论】:

    标签: objective-c ios uitoolbaritem


    【解决方案1】:

    这对我来说适用于 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;
    }
    

    【讨论】:

      【解决方案2】:

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

      希望这会有所帮助。

      【讨论】:

      • 你是我的男人,我本可以弄清楚我自己 - 它就像一个魅力
      猜你喜欢
      • 2011-11-29
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多