UIBarButtonItem 的 UIButton 扩展

UIButton Extension For UIBarButtonItem

我正在通过使用 swift 文件编写扩展,并按以下方式编写代码:

import Foundation
import UIKit

extension UIButton{

    func backButtonTarget(_ target: Any, action: Selector) -> UIBarButtonItem {
        let backButton = UIButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(12), height: CGFloat(20)))
        backButton.setBackgroundImage(UIImage(named: "back.png"), for: .normal)
        let barBackButtonItem = UIBarButtonItem(customView: backButton)
        backButton.addTarget(target, action: action, for: .touchUpInside)
        return barBackButtonItem
    }


}

现在,我尝试通过以下方式在我需要的 viewcontroller 中声明一个按钮来使用它:

var backButton: UIButton! = nil

并在我的 viewDidLoad 中声明以下代码:

self.navigationItem.leftBarButtonItem = backButton?.backButtonTarget(self, action: #selector(self.popCurrentViewController))

并在 popCurrentViewController

func popCurrentViewController() -> Void {

            _ = self.navigationController?.popViewController(animated: true)

    }

在这里,通过声明上面的代码,UINavigationBar 左栏项目按钮应该按照我创建的按钮显示,但它没有显示,也没有进入扩展功能,但是通过使用完美地处理 Objective c 代码类别,我在哪里做错了?任何帮助将不胜感激。

谢谢

navigationBar 中没有按钮是因为你的 backButton 是 nil,目前你已经添加了实例方法的扩展而不是你需要 class 方法。

extension UIButton {

    class func backButtonTarget(_ target: Any, action: Selector) -> UIBarButtonItem {
        let backButton = UIButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(12), height: CGFloat(20)))
        backButton.setBackgroundImage(UIImage(named: "back.png"), for: .normal)
        let barBackButtonItem = UIBarButtonItem(customView: backButton)
        backButton.addTarget(target, action: action, for: .touchUpInside)
        return barBackButtonItem
    }
}

现在用这种方式添加BarButtonItem

self.navigationItem.leftBarButtonItem = UIButton.backButtonTarget(self, action: #selector(self.popCurrentViewController))