Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom button to navigation controller without border

I add custom button to navigation controller

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"]
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = backButton;

it works fine, but button appears bordered. How can I fix that?

UPDATE I found solution

   
 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonFavoriteClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button release];
 
self.navigationItem.leftBarButtonItem = back;
like image 231
Tunyk Pavel Avatar asked Apr 11 '11 12:04

Tunyk Pavel


2 Answers

Try this.

UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, button_width, button_height)];
[backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
like image 123
EmptyStack Avatar answered Nov 03 '22 22:11

EmptyStack


For Swift 4

let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
backButton.setImage(UIImage(named: "back.png"), for: .normal)
backButton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: backButton)

And action (selector) should be like the following :

@objc func backAction () {
        // do the magic 
}
like image 3
Mostafa Sultan Avatar answered Nov 04 '22 00:11

Mostafa Sultan