关于xcode:将自定义按钮添加到没有边框的导航控制器

Add custom button to navigation controller without border

我将自定义按钮添加到导航控制器

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

它工作正常,但按钮似乎有边框。我怎样才能解决这个问题?

更新我找到了解决办法

1
2
3
4
5
 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];
1
self.navigationItem.leftBarButtonItem = back;


试试这个。

1
2
3
4
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];

斯威夫特4

1
2
3
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)

操作(选择器)应该如下所示:

1
2
3
@objc func backAction () {
        // do the magic
}