RxSwift-表格视图中的Textfield-Variable绑定 [英] RxSwift - Textfield-Variable binding in tableview
问题描述
我是RxSwift的新手,我有以下代码来设置一个包含文本字段的表格视图:
I'm new to RxSwift and I have this code to setup a tableview which contains a textfield:
budget.expenses.asObservable()
.bindTo(tableView.rx.items(cellIdentifier: ExpenseInputCell.cellIdentifier, cellType: ExpenseInputCell.self)){(row, element, cell) in
cell.name.text = element.name.value
cell.name.rx.text
.bindTo(element.name)
.addDisposableTo(self.disposeBag)
}
.addDisposableTo(disposeBag)
tableView.rx.itemDeleted
.subscribe(onNext: {indexPath in
self.budget.expenses.value.remove(at: indexPath.row)
})
.addDisposableTo(disposeBag)
一切正常,直到删除一行为止,因为这样会将文本字段与数组中正确对象的绑定混合在一起.例如,假设我在表视图中有7个项目,并且删除了第5行,新的第5行和第6行的值都相同
Everything works fine until a row is deleted, because then the binding of the textfield to the correct object in the array is mixed up. For example lets say I have 7 items in the tableview and I delete the 5th row, the new 5th and 6th row both have the same value
推荐答案
问题出在element.name
订阅的生命周期中.因为它与self.disposeBag
绑定,所以当单元被重用时,它不会被释放,而当self
被使用时,它不会被释放.
The problem lies in the lifecycle of the subscription to element.name
. Because it is tied to self.disposeBag
, it will not be dismissed when the cell is reused, but when self
is.
您可能想在ExpenseInputCell
上暴露一个新的处理袋,并通过单元格的prepareForReuse
方法对其进行更新.
You probably want to expose a new dispose bag on ExpenseInputCell
and renew it in cell's prepareForReuse
method.
class ExpenseInputCell: UITableViewCell {
// ..
var disposeBag = DisposeBag()
override func prepareForReuse() {
self.diposeBag = DisposeBag()
}
}
并在视图控制器中
budget.expenses.asObservable()
.bindTo(tableView.rx.items(cellIdentifier: ExpenseInputCell.cellIdentifier, cellType: ExpenseInputCell.self)){(row, element, cell) in
cell.name.text = element.name.value
cell.name.rx.text
.bindTo(element.name)
.addDisposableTo(cell.disposeBag)
}
.addDisposableTo(disposeBag)
这篇关于RxSwift-表格视图中的Textfield-Variable绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!