RxSwift只触发一次

时间:2018-01-05 06:53:03

标签: ios swift uisearchbar uisearchcontroller rx-swift

searchController.searchBar.rx.text
            .asDriver()
            .map{ $0 == "" || $0 == nil }
            .drive(onNext: { (empty) in
                if empty {
                    print("Search empty")
                } else {
                    print("!!!!!!!!!!!!! empty")
                }
            }).disposed(by: disposeBag)

这将在第一次启动时调用,第二次在我键入第一个字符串时调用,但不再有效,错误在哪里?谢谢!

1 个答案:

答案 0 :(得分:1)

我检查了你的代码,发现设置UISearchBar的委托只会使驱动程序触发一次。例如:

self.searchController.searchBar.delegate = self

如果未设置委托 - 驱动程序会按预期触发。所以你应该对搜索代表做一些事情,并检查它是否有助于你解决问题。

这是一个表示此行为的示例项目:

import Foundation
import UIKit
import RxCocoa
import RxSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds)

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window?.rootViewController = UINavigationController(rootViewController: Controller())
        window?.makeKeyAndVisible()
        return true
    }
}

final class Controller: UIViewController, UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {

    lazy var disposeBag = DisposeBag()
    lazy var searchController = UISearchController(searchResultsController: nil)

    init() {
        super.init(nibName: nil, bundle: nil)
        self.view.backgroundColor = UIColor.orange
        self.searchController.searchResultsUpdater = self
        self.searchController.hidesNavigationBarDuringPresentation = false
        self.navigationItem.titleView = self.searchController.searchBar
        self.definesPresentationContext = true
        self.searchController.delegate = self
        self.searchController.dimsBackgroundDuringPresentation = false
        // self.searchController.searchBar.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.searchBar.rx.text
            .asDriver()
            .map{ $0 == "" || $0 == nil }
            .drive(onNext: { (empty) in
                if empty {
                    print("Search empty")
                } else {
                    print("!!!!!!!!!!!!! empty")
                }
            })
            .disposed(by: disposeBag)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func updateSearchResults(for searchController: UISearchController) {
        //
    }
}