Somehow combine with search controller not working, any idea?

一曲冷凌霜 提交于 2020-06-01 07:35:27

问题


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 ?? "")
        }

    }
}

回答1:


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.

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.



来源:https://stackoverflow.com/questions/60241335/somehow-combine-with-search-controller-not-working-any-idea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!