以某种方式与搜索控制器结合不起作用,有什么主意吗? [英] Somehow combine with search controller not working, any idea?

查看:54
本文介绍了以某种方式与搜索控制器结合不起作用,有什么主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,当我在搜索字段中键入内容时,它不会在Xcode控制台上打印出"str".我在这里想念什么?我按照他的教程 https://www.letsbuildthatapp.com/course_video?id=5232

For some reason when I type in the search field it does not print out Xcode console the "str". What am I missing here? I followed his tutorial https://www.letsbuildthatapp.com/course_video?id=5232

import UIKit

class SearchViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    var sink: Any?

    override func viewDidLoad() {
        super.viewDidLoad()

        setupSearchBarListener()

        navigationItem.searchController = searchController

        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.title = "Contact"

        searchController.obscuresBackgroundDuringPresentation = false

        view.backgroundColor = .white
    }

    fileprivate func setupSearchBarListener() {

        let publisher = NotificationCenter.default.publisher(for: UISearchTextField.textDidChangeNotification, object: searchController.searchBar.searchTextField)
        publisher
            .map {
            ($0.object as! UISearchTextField).text
        }
            .debounce(for: .milliseconds(500), scheduler: RunLoop.main)
            .sink { (str) in
                print(str ?? "")
        }

    }
}

推荐答案

您正在使用 .sink 方法创建一个Sink对象,但没有将其存储在任何地方.因此,它立即不存在了,没有发布的渠道.

You are creating a Sink object with the .sink method, but you are not storing it anywhere. Therefore it goes out of existence immediately and there is no pipeline to publish to.

此处正确的过程是将实例属性键入为 Set< AnyCancellable> ,然后在接收器上调用 store(in:)将其存储在该实例属性中.现在它将持续存在,并且会有一些内容要打印出来.

The correct procedure here is to have an instance property typed as Set<AnyCancellable> and call store(in:) on your sink to store it in that instance property. Now it will persist and there will be something to print out.

这篇关于以某种方式与搜索控制器结合不起作用,有什么主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆