7

如图所示,我已向导航栏的自定义右栏按钮项添加了一个自定义按钮。

我希望能够删除按钮后的空格,以便它触摸屏幕的右边缘,但即使在搜索后也找不到解决方案。如果有人能提到如何,那就太好了。

这是我正在使用的代码

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
aButton.frame = CGRectMake(50.0, 0.0, 60, 44);
UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
[aButton addTarget:self action:@selector(testButtonControl:) forControlEvents:UIControlEventTouchUpInside];

self.navigationItem.rightBarButtonItem = aBarButtonItem;

在此处输入图像描述

4

4 回答 4

17

您可以添加一个具有负宽度的固定空间元素(我知道,这听起来像是一个 hack,但它有效):

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
aButton.frame = CGRectMake(50.0, 0.0, 60, 44);
UIBarButtonItem *aBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:aButton];
[aButton addTarget:self action:@selector(testButtonControl:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *spaceFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
spaceFix.width = -5;

self.navigationItem.rightBarButtonItems = @[spaceFix, aBarButtonItem];
于 2013-06-05T17:49:31.487 回答
3

您必须创建一个新视图,添加按钮和您想要的所有其他内容,并将其添加到 titleView,如图所示。

- (void)viewDidLoad {
    self.navigationItem.titleView = [self titleView];
}

- (UIView *)titleView {
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat width = 0.95 * self.view.frame.size.width;
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, navBarHeight)];
..
// please add what you need here
....
}
于 2012-09-07T11:23:43.407 回答
0

你不能,除非你UINavigationBar通过类别继承或覆盖它的方法。

于 2012-08-05T09:00:04.607 回答
0

您可以通过添加 UIView 来做到这一点,然后在其中添加 x=spaceWidth y = 0 的按钮。

查看下面的代码以获取正确的项目(这是在 UINavigationItem 类别中)

1 -

UIView *_rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)]; [_rightView setBackgroundColor:[UIColor purpleColor]];//debug color

2-

    UIButton *aLeftButton = [[UIButton alloc] init];

   //...//

    aLeftButton.frame = CGRectMake(-15, 0, 44, 44);//in your case +15
    [aLeftButton setBackgroundImage:[UIImage imageNamed:buttonName] forState:UIControlStateNormal];
    [aLeftButton setBackgroundImage:[UIImage imageNamed:[buttonName stringByAppendingString:@"Selected"]] forState:UIControlStateSelected];
    [aLeftButton setAdjustsImageWhenDisabled:NO];
    [aLeftButton setAdjustsImageWhenHighlighted:NO];

    [aLeftButton addTarget:theSender action:aSelector forControlEvents:UIControlEventTouchUpInside];
    [_rightView addSubview:aLeftButton];
    UIBarButtonItem *aBarButton = [[UIBarButtonItem alloc] initWithCustomView:_rightView];
    [leftBarButtonsItem addObject:aBarButton];`

3

self.leftBarButtonItem = leftBarButtonsItem;

于 2013-11-01T14:46:26.513 回答