美文网首页
iOS导航栏自定义返回按钮事件

iOS导航栏自定义返回按钮事件

作者: 姬歌 | 来源:发表于2018-12-10 20:33 被阅读28次

通常自定义的leftBarButtonItems距离左侧边距有十万八千里元,让人看见就要反胃,但苹果就是这么吊,就是要你自定义的就必须这么丑!下面的方法目前可以解决这个问题。

  • 先自定义一个UIButton:
import UIKit
class JKNavigationItemCustomView: UIButton {
    var alignmentRectInsetsOverride = UIEdgeInsets.zero
    override var alignmentRectInsets: UIEdgeInsets {
        if UIEdgeInsetsEqualToEdgeInsets(alignmentRectInsetsOverride, UIEdgeInsets.zero) {
            return super.alignmentRectInsets
        }else {
            return self.alignmentRectInsetsOverride
        }
    }
}

然后在ViewController中自定义leftBarButtonItems

override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
}

func setupUI() {
        let offset: CGFloat = 8
        let backBtn = JKNavigationItemCustomView(type: .custom)       //JKNavigationItemCustomView
        let backBtnW: CGFloat = 22.0
        let backBtnH: CGFloat = 42.0
        backBtn.frame = CGRect(x: 0, y: 0, width: backBtnW, height: backBtnH)
        
        backBtn.setImage(UIImage(named: "backbarbutton"), for: .normal)
        backBtn.addTarget(self, action: #selector(baseBackButtonClick(_ :)), for: .touchUpInside)
        let backItem = UIBarButtonItem(customView: backBtn)
        
        if #available(iOS 11.0, *) {
            backBtn.alignmentRectInsetsOverride = UIEdgeInsetsMake(0, offset, 0, -offset)
            backBtn.translatesAutoresizingMaskIntoConstraints = false
            backBtn.widthAnchor.constraint(equalToConstant: backBtnW).isActive = true
            backBtn.heightAnchor.constraint(equalToConstant: backBtnH).isActive = true
        }
        
        let fixSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        fixSpaceItem.width = -offset
        navigationItem.leftBarButtonItems = [fixSpaceItem, backItem]
}

图片周边留有适量空白


44x80 66x120

相关文章

网友评论

      本文标题:iOS导航栏自定义返回按钮事件

      本文链接:https://www.haomeiwen.com/subject/qggdhqtx.html