Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setImage method changes UIBarButtonItem width, even if image size doesn't change

I want to add a "bookmark" button to my navigation bar as a rightBarButtonItem

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Add bookmark button
    UIBarButtonItem *bookmarkBarButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:@selector(bookmark:)];
    [bookmarkBarButton setImage:[UIImage imageNamed:@"greyBookmark.png"]];
    [self.navigationItem setRightBarButtonItem:bookmarkBarButton];
    bookmarkBarButton.tintColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:0.9f];
    b_bookmarked = false;
}

// Will call this method when the bookmark button is pressed
- (IBAction)bookmark:(id)sender
{
    // Toggle color of bookmark icon on button
    if ( (b_bookmarked = !b_bookmarked) )
    {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"blueBookmark.png"]];
    }
    else
    {
        [self.navigationItem.rightBarButtonItem setImage:[UIImage imageNamed:@"greyBookmark.png"]];
    }

    // Save bookmark

}

both greyBookmark.png and blueBookmark.png have 10x26 size. Button looks narrowed when view appears. But when I click this button, button gets wider, image still changes though. Width changes when setImage method is called in bookmark: method (gets back to default size). I tried to explicitly set the width by calling [navigationItem.rightBarButtonItem setWidth:] - doesn't help either. Before doing that, width property was set to 0 and button should have resize depending on its image size, according to documentation.

I want the rightBarButtonItem to have a const width. Is there a reason why it gets wider after the second call to setImage?

like image 639
AzaFromKaza Avatar asked Mar 01 '13 01:03

AzaFromKaza


1 Answers

UIImage *myImage = [UIImage imageNamed:@"greyBookmark.png"];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setImage:myImage forState:UIControlStateNormal];
myButton.showsTouchWhenHighlighted = YES;
myButton.frame = CGRectMake(0.0, 3.0, 70,30);
[myButton addTarget:self action:@selector(BookmarkButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightbutton = [[UIBarButtonItem alloc] initWithCustomView:myButton];
self.navigationItem.rightBarButtonItem = rightbutton;

Put this method under viewDidLoad

-(void)BookmarkButtonPressed

{

      //Do ur work here for Button Action

}
like image 125
Hari1251 Avatar answered Oct 13 '22 11:10

Hari1251