IPhone UINavigationBar - setting the width and margin of rightBarButtonItem

I have a background image for a button with dimensions of 80x30 pixels.

I use the code below to set the background in my view controller, and the result will be the following:

Top and corners are noisy

As you can see, the corners and top of the right button are mixed up.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIImage *favoriteBtnImgNormal = [[UIImage imageNamed:@"favorite-btn-normal"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];
    UIImage *favoriteBtnImgTouch = [[UIImage imageNamed:@"favorite-btn-touch"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];

    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setTitlePositionAdjustment:UIOffsetMake(-10.0, 0.0) forBarMetrics:UIBarMetricsDefault];
}

Please note that I do this in one view controller, I use the appearance API to set general styles. But here I want to redefine the overall look.

If I just get images without resizable, it looks like this:

Too large

Now the edges and corners are fine, but the button is too big.

I'm sure I'm doing it all wrong, so I need someone to point out what I can do to scale the buttons correctly?

+3
source share
1 answer
UIImage *image = [UIImage imageNamed:@"YourImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );

[button setImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(YourAction) forControlEvents:UIControlEventTouchUpInside];

button.contentEdgeInsets = (UIEdgeInsets){.right=-10};

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
0
source

All Articles