我在导航栏的自定义右键栏项目中添加了一个自定义按钮,如图所示。
我希望能够删除按钮后的空格,使其触及屏幕的右边缘,但即使搜索后也无法找到解决方案。如果有人能提到怎么样,会很棒。
这是我正在使用的代码
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;
答案 0 :(得分: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];
答案 1 :(得分: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
....
}
答案 2 :(得分:0)
除非您继承UINavigationBar
或通过类别覆盖其方法,否则不能。
答案 3 :(得分: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;