![](/img/trans.png)
[英]Cannot set bind(to: UITableView) with RxSwift Variable asObservable()
[英]How to bind UISearchBar to UITableView with RxSwift
我有一個數字數組,我希望tableview
顯示我在搜索欄中輸入的數字。 這是我的代碼,我不知道我應該在(而不是) .subscribe
之后的行中寫什么
let dataSource = BehaviorRelay(value: [String]())
let disposeBag = DisposeBag()
var numbers = ["1", "2", "3", "4", "5"]
override func viewDidLoad() {
super.viewDidLoad()
dataSource.accept(numbers)
searchBar.rx.text.orEmpty
.throttle(.milliseconds(2000), scheduler: MainScheduler.instance)
.filter{self.numbers.contains($0)}
.subscribe(onNext:
})
self.dataSource
.asObservable()
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: TableViewCell.self)) {(row, element, cell) in
cell.textLabel?.text = element
}
.disposed(by: disposeBag)
可能因為其他原因無法使用,還是謝謝大家幫忙
您想將響應式代碼視為因果鏈。 發生一些副作用會導致一些其他副作用。 當然在因果之間你有業務邏輯。
首先請注意,不需要主題。 在Intro To Rx一書中,我們了解到:
受試者提供了一種方便的方式來查看 Rx,但不建議將它們用於日常使用。
現在我們在思考“因果關系”......我們想要達到的效果是什么? 那將是表視圖的 output :
這是三個原因和定義原因如何影響結果的邏輯。
final class Example: UIViewController {
var searchBar: UISearchBar!
var addButton: UIButton!
var deleteButton: UIButton!
var tableView: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
enum Input {
case add
case delete
}
let initial = ["1", "2", "3", "4", "5"] // this is what we start with
Observable.merge(
addButton.rx.tap.map { Input.add }, // flag addButton taps for adding a number
deleteButton.rx.tap.map { Input.delete } // flag deleteButton taps for deleting a number
)
.scan(into: initial) { state, input in // setup a state machine that:
switch input {
case .add:
state.append("\(state.count + 1)") // adds a number when the add event happens
case .delete:
state.removeLast() // removes the last number when a delete event happens
}
}
.withLatestFrom(searchBar.rx.text) { list, text in
list.filter { $0 == text } // here we filter the list based on the value in the search bar
}
.startWith(initial) // show the initial values at start
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { _, element, cell in
cell.textLabel?.text = element
}
.disposed(by: disposeBag)
}
}
您可能希望使過濾器比我上面的過濾器更復雜或更簡單。 為了使上述內容可測試,只需將閉包移到單獨的函數中,以便可以獨立測試它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.