Add custom button to navigation controller without

2019-02-06 17:28发布

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;

2条回答
Viruses.
2楼-- · 2019-02-06 17:49

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];
查看更多
Evening l夕情丶
3楼-- · 2019-02-06 17:52

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 
}
查看更多
登录 后发表回答