31

如何删除自定义左右 UINavigationBar 项目左右的水平填充?iOS 默认设置的填充点似乎约为 10 点。

我正在自定义左右导航栏按钮(我已经放弃尝试设置自己的backButtonItem,所以我只使用leftBarButtonItem)。

在任何一种情况下(左或右),按下这些自定义按钮都表明 Apple 似乎在 leftBarButtonItem 的左侧和 rightBarButtonItem 的右侧保留了一些填充;无论我制作 UIButton 的自定义背景和图像属性有多宽,我都将其放置在左/右栏按钮项内作为其自定义视图。

由于 UIBarButtonItems 没有我可以访问的“框架”,因此我不能像普通 UIViews 那样将它们定位在它们的超级视图中。

有关如何删除此默认填充的任何建议?请参阅所附的屏幕截图以查看我试图减小到零宽度的位。在屏幕截图中,加号图标似乎向右移动,因为我给了它一个插图;但是突出显示的背景图像,也可能使用该插图,在其右侧被剪裁)。

参见图片:https ://skitch.com/starbaseweb/rj2e5/ios-simulator

作为参考,这是我创建自定义 UIBarButtonItem 的方式(在这种情况下,它是右键):

- (UIBarButtonItem *)customAddButtonItemWithTarget:(id)target action:(SEL)action {
  UIButton *customButtonView = [UIButton buttonWithType:UIButtonTypeCustom];

    customButtonView.frame = CGRectMake(0.0f, 0.0f, 45.0f, 44.0f);

    [customButtonView setBackgroundImage:
        [UIImage imageNamed:@"bgNavBarButton-OutsideRight-Normal.png"] 
        forState:UIControlStateNormal];
    [customButtonView setBackgroundImage:
        [UIImage imageNamed:@"bgNavBarButton-OutsideRight-Highlighted.png"] 
        forState:UIControlStateHighlighted];

    [customButtonView setImage:
        [UIImage imageNamed:@"bgNavBarButton-Add-Normal.png"] 
        forState:UIControlStateNormal];
    [customButtonView setImage:
        [UIImage imageNamed:@"bgNavBarButton-Add-Highlighted.png"] 
        forState:UIControlStateHighlighted];

    [customButtonView addTarget:target action:action 
        forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *customButtonItem = [[[UIBarButtonItem alloc] 
        initWithCustomView:customButtonView] autorelease];
    [customButtonView setImageEdgeInsets:UIEdgeInsetsMake(0.0f, 10.0f, 0.0f, 0.0f)];

    //customButtonItem.imageInsets = UIEdgeInsetsMake(0.0f, 10.0f, 0.0f, 0.0f);

    return customButtonItem;    
}
4

2 回答 2

83

55如上所述,我采用的解决方案是基于对一个不同但非常相关的问题的答案:如何调整 UIToolBar 左右填充。iOS5 也为它提供了便利(并且依赖于),它允许您在左侧或右侧设置多个按钮,而不仅仅是一个。

这是一个删除自定义左按钮项左侧填充的示例:

UIBarButtonItem *backButtonItem // Assume this exists, filled with our custom view

// Create a negative spacer to go to the left of our custom back button, 
// and pull it right to the edge:
UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] 
    initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace 
    target:nil action:nil];
negativeSpacer.width = -5; 
// Note: We use 5 above b/c that's how many pixels of padding iOS seems to add

// Add the two buttons together on the left:
self.navigationItem.leftBarButtonItems = [NSArray 
    arrayWithObjects:negativeSpacer, backButtonItem, nil];

这样,导航栏中左侧栏按钮项的左侧填充就消失了!

注意:这在 iOS5 和 iOS6 中对我有用。鉴于 iOS7 与公开演示有很大不同,那些拥有 iOS7 早期种子的人应该测试这种无意的东西,比如这个 hack,是否真的会在 iOS6 之后继续为你工作。

于 2011-11-09T19:54:07.327 回答
3

我已经尝试过了,它有效:

1) 创建一个自定义的 UIToolbar 子类,它在 -drawRect: 中什么都不做,并且不是不透明的,并且具有 backgroundColor = [UIColor clearColor]。

2) 创建一个自定义 UIBarButtonItem ,将工具栏作为自定义视图。

3) 将您的按钮添加到自定义工具栏。

4)在您的自定义工具栏中覆盖 -layoutSubviews 并做自己的间距。

于 2011-03-03T19:09:09.360 回答