问题:某些情况下我们需要自定义返回按钮 如下图在添加的
leftBarButtonItem
会向右偏移一点
- iOS11以前(可以通过以下方法处理)
但是iOS11以后以下方法失效
let leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "返回白"), style: UIBarButtonItem.Style.done, target: self, action: #selector(backBtnClick))
let nagetiveSpacer = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
nagetiveSpacer.width = -11//这个值可以根据自己需要自己调整
navigationItem.leftBarButtonItems = [nagetiveSpacer, leftBarButtonItem]
Swift
- 解决方案(当前以iOS11为节点做处理)
public func setBackBtn(_ tintColor: UIColor = .black) {
let leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "返回白"), style: UIBarButtonItem.Style.done, target: self, action: #selector(backBtnClick))//
leftBarButtonItem.tintColor = tintColor
if #available(iOS 11.0, *){ // ios11 以上偏移
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 0, left: -11, bottom: 0, right: 0)
navigationItem.leftBarButtonItem = leftBarButtonItem
} else {
let nagetiveSpacer = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
nagetiveSpacer.width = -11//这个值可以根据自己需要自己调整
navigationItem.leftBarButtonItems = [nagetiveSpacer, leftBarButtonItem]
}
if (navigationController?.viewControllers.count ?? 0) > 1 {
navigationController?.interactivePopGestureRecognizer?.delegate = self as? UIGestureRecognizerDelegate // 重要 自定义返回按钮恢复返回手势
}
}
@objc private func backBtnClick() {
dismiss(animated: true, completion: nil)
navigationController?.popViewController(animated: true)
}
OC
// MARK: - 快速添加返回按钮 并让边缘手势生效
- (void)setBackButton {
UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backButtonClick)];
if (@available(iOS 11.0, *)) {
leftBarButtonItem.imageInsets = UIEdgeInsetsMake(2, -8, 0, 0);
self.navigationItem.leftBarButtonItem = leftBarButtonItem;
} else {
UIBarButtonItem *nagetiveSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFixedSpace) target:nil action:nil];
nagetiveSpacer.width = -8; //这个值可以根据自己需要自己调整
self.navigationItem.leftBarButtonItems = @[leftBarButtonItem, leftBarButtonItem];
}
if (self.navigationController.viewControllers.count > 1) {
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)backButtonClick {
[self dismissViewControllerAnimated:YES completion:nil];
}