如何在自定义 UISearchBar 子类中使用委托方法

How to use delegate methods in a custom UISearchBar subclass

我正在尝试创建自定义 UISearchBar,但在尝试使用 UISearchBar 的委托方法时遇到了问题。我正在使用以下代码,但它不起作用?我做错了什么?

class CustomSearchBar: UISearchBar, UISearchBarDelegate {
    
    var searchDelegate: UISearchBarDelegate

    init(del: UISearchBarDelegate) {
        self.searchDelegate = delegate
        super.init(frame: .zero)
        sizeToFit()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
    }
}

应该实现 UISearchBarDelegate 协议的 class 是 ViewController,您将在其中显示此搜索栏。在视图控制器中你会有这样的东西:

class VC: UIViewController {

    let searchBar = CustomSearchBar()

    searchBar.delegate = self
}

extension VC: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
    }
}

在尝试了几件事之后,我找到了一种访问委托的方法。我用了searchTextField.addTarget(self, action: #selector(searchBar(_:)), for: .editingDidEnd)。这允许我在 UISearchBar 中更改文本时进行访问。