[英]RxSwift only trigger once
searchController.searchBar.rx.text
.asDriver()
.map{ $0 == "" || $0 == nil }
.drive(onNext: { (empty) in
if empty {
print("Search empty")
} else {
print("!!!!!!!!!!!!! empty")
}
}).disposed(by: disposeBag)
This will be called once the first time it is started, the second one when I type the first string, but will not be valid anymore,where the error? 第一次启动时将调用此方法,当我键入第一个字符串时将调用第二个方法,但是它将不再有效,哪里出错了? thank!!! 谢谢!!!
I have checked your code and found that setting UISearchBar
's delegate makes the driver to fire only once. 我检查了您的代码,发现设置UISearchBar
的委托会使驱动程序仅触发一次。 For example: 例如:
self.searchController.searchBar.delegate = self
If the delegate isn't set - the driver fires as you expect. 如果未设置委托,则驱动程序将按预期触发。 So you should do something with search delegates and check whether it helps you to solve the problem. 因此,您应该对搜索委托执行某些操作,并检查它是否有助于解决问题。
This is a sample project which represents this behavior: 这是一个代表此行为的示例项目:
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) {
//
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.