I want the bar button item in the navigation bar to be placed at the extreme corner of the navigation bar

StackOverflow https://stackoverflow.com/questions/20917586

When i try the following code, the bar-button comes with about 30px spacing from the edge,

But i want it to be just 2 pixels away from the edge. Any way to do so?

I want the bar button only, and not a custom UIButton.

UIImage* buttonImage = [UIImage imageNamedH568: @"publish_button.png"];

UIButton * clearButton = [UIButton buttonWithType: UIButtonTypeCustom];

clearButton.frame           = CGRectMake(244.0f, 5.0f, 65.0f, 33.0f);
clearButton.titleLabel.font = [Utils helveticaBoldFontOfSize: 12.0f];

[clearButton setBackgroundImage: buttonImage                        forState: UIControlStateNormal];
[clearButton setTitle:           NSLocalizedString(@"Clear", nil) forState: UIControlStateNormal];
[clearButton setTitleColor:      [UIColor whiteColor]               forState: UIControlStateNormal];

[clearButton addTarget: self action: @selector(clearNotificationsList:) forControlEvents: UIControlEventTouchUpInside];

UIBarButtonItem* clearItem = [[UIBarButtonItem alloc] initWithCustomView: clearButton];

self.navigationItem.rightBarButtonItem = clearItem;
有帮助吗?

解决方案

Added the following two function from UINavigationItem-iOS7Spacing

 - (UIBarButtonItem *)spacer
{
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    space.width = -11;
    return space;
}

- (BOOL)isIOS7
{
    return ([[[UIDevice currentDevice] systemVersion] compare:@"7" options:NSNumericSearch] != NSOrderedAscending);
}

And then used the following inside loadView -

 UIBarButtonItem* clearItem = [[UIBarButtonItem alloc] initWithCustomView: clearButton];

    if ([self isIOS7]) {
        self.navigationItem.rightBarButtonItems = @[[self spacer],clearItem];
    }
    else
    {
        self.navigationItem.rightBarButtonItem = clearItem;
    }

Worked Flawlessly

Thank you all for your help!

其他提示

Setting the frame will not do the trick here.

You have to use the following for the image:

[clearButton setBackgroundImage:[[UIImage imageNamed:@"publish_button"] imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, - 10 : 0 , 0, 0)] forState:UIControlStateNormal];// -10 or something that suits you.

And the following for the title:

clearButton.titleEdgeInsets = UIEdgeInsetsMake(0, - 10, 0, 0);

EDIT:

Alternatively, you can use the following for both:

clearButton.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);

better use UINavigationItem-iOS7Spacing Category

https://github.com/marius-/UINavigationItem-iOS7Spacing

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top