如何删除旁边的UIBarButtonItem填充(How to remove padding nex

2019-06-26 19:10发布

我添加了一个自定义按钮,导航栏的自定义权限栏按钮项所示的形象。

我希望能够按钮后删除空间,以便触摸屏幕的右侧边缘,但即使搜索后无法找到一个解决方案。 如果有人能提到如何,将是巨大的。

这是我使用的代码

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;

Answer 1:

你可以用一个负宽度增加一个固定的空间元素(我知道,这听起来像一个黑客,但它的工作原理):

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];


Answer 2:

你必须创建一个新视图,添加按钮和一切你想要和它,如添加到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
....
}


Answer 3:

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



Answer 4:

您可以通过添加一个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;



文章来源: How to remove padding next to a UIBarButtonItem