如何删除UIBarButtonItem旁边的填充

car*_*onr 5 xcode uinavigationbar uibarbuttonitem

我在导航栏的自定义右键栏项目中添加了一个自定义按钮,如图所示.

我希望能够删除按钮后的空格,使其触及屏幕的右边缘,但即使在搜索后也无法找到解决方案.如果有人能提到怎么样,会很棒.

这是我正在使用的代码

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;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Tom*_*Tom 17

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

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];
Run Code Online (Sandbox Code Playgroud)


car*_*onr 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
....
}
Run Code Online (Sandbox Code Playgroud)