Search code examples
objective-ciosprogramming-languages

ios) Object-c. how to customize a button on the navigation bar


I'm developing a navigation-base application with a custom navigation bar. I succeeded to have a navigation bar with an image and a button. However I have no idea how to make the custom button..:(

This is the code that adds the "main"button on the navigation bar.(in the view controller, initWithNibName method)

if (self) {
    // Custom initialization.

    //set navigation id to I to inform that that page is inforview
    navID = @"I";

            //adds the button on the navigation bar
    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Main" style:UIBarButtonItemStyleBordered target:self action:@selector(goBack:)];
    self.navigationItem.leftBarButtonItem = button;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [button release];
    [navID release];

}

Thank you

I created a custom button and applied it to the UIbarbuttonitem. There is no error but nothing is shown on the navigation bar:( This is my code-

    //create a custom button
    UIImage *image = [UIImage imageNamed:@"TESTButton.png"];
    UIButton *myCustomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myCustomButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [myCustomButton setImage:image forState:UIControlStateNormal];
    [myCustomButton addTarget:nil action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];


    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithCustomView:myCustomButton];
    self.navigationItem.leftBarButtonItem = button;
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;

Anybody who can fix my code? :)


Solution

  • The easiest way is to use:

    UIButton *yourCustomButton = ....
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:yourCustomButton];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    [barButtonItem release];