ios - iOS 11 UISearchController 上的 UIToolbar 按钮未调用操作

标签 ios swift uitoolbar ios11 uisearchcontroller

NavigationItem适配iOS 11新的UISearchController后,遇到了一些问题。

我已将 UIBarButtonItem 添加到 UISearchController 的搜索栏的工具栏中。单击此按钮时会调用一个函数(作为 UIBarButtonItem 构造函数中的操作参数传递)。

在 iOS 11 之前,搜索栏已附加到 tableHeaderView,这非常有效(并且仍然有效)。单击按钮时调用该函数。

但是,在 iOS 11 中,即使实现相同,也不会调用该函数。

任何想法可能是错误的?或者是 iOS 11 中的错误?

    private func setupSearchController() {

        ... 

        let toolbar = UIToolbar()
        toolbar.sizeToFit()

        // Create bar button item with image.
        let qrBarButton = UIBarButtonItem(image: #imageLiteral(resourceName: "QR Code"), style: .plain, target: nil, action: #selector(didPressQRToolbarButton))

        // Add the new button.
        toolbar.items = [qrBarButton]

        searchController.searchBar.inputAccessoryView = toolbar

        // If the device is on iOS 11, use the "native" search bar placement.
        if #available(iOS 11.0, *) {
            navigationItem.searchController = searchController

            // Don't use the large title in the navigation bar.
            navigationController?.navigationBar.prefersLargeTitles = false
        } else {
            // Handled in subclasses.
        }
    }

    /// Action for the QR toolbar button
    func didPressQRToolbarButton(sender: Any) {
        ...
        // NOT CALLED
    }

最佳答案

首先,检查函数 func didPressQRToolbarButton(sender: Any) 的发送者。 应该是这样的:

func didPressQRToolbarButton(sender: UIBarButtonItem)

然后,您一定从 xCode 收到了一些警告,因为 自动 @objc 推断在 Swift 4 上已被弃用。

因此,在 Swift 4 上,didPressQRTToolbar 或作为参数传递给 #selector 的任何函数:

#selector(didPressQRToolbarButton)

必须在其声明中添加@objc:

@objc func didPressQRToolbarButton(sender: Any) {

关于ios - iOS 11 UISearchController 上的 UIToolbar 按钮未调用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46463204/

相关文章:

ios - 如何为 native iOS 应用程序创建测试用户?

ios - UIToolbar 和状态栏之间应该有边框吗?

ios - iOS7上的UIToolbar样式

ios - uitextview 在键盘顶部快速添加像笔记应用程序一样的 uitoolbar

android - 将应用程序构建为 Web 应用程序以实现更轻松的多平台兼容性是个好主意吗?

iOS Facebook 登录不起作用

ios - SwiftUI HStack不会达到最高水平吗?

swift - 如何更改代码以从 Firebase 存储而不是本地下载文件

ios - 从另一个文件快速访问变量

ios - 在tableview中插入和删除单元格,将文本字段放入单元格中,然后将文本字段数据放入swift中的json原始参数中