【问题标题】:RxSwift with CollectionView/TableView Input/ textfields带有 CollectionView/TableView 输入/文本字段的 RxSwift
【发布时间】:2017-04-05 09:23:13
【问题描述】:

我正在尝试掌握 RxSwift,我需要验证表单,我已经完成了没有 tableView 的简单验证,但是现在我的文本输入字段在集合视图中,我想观察文本输入的变化,因为文本字段现在在可重复使用的单元格,我不确定如何添加可观察对象并从中获取流

基本上我希望将我的数据以两种方式绑定到我的表单,其中输入是动态的,如果有帮助的话

这是我的 cellForItemAt 函数的代码

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RegisterCell.identifier, for: indexPath) as! RegisterCell
    var registerField = dataSource[indexPath.item]
    registerField.indexPath = indexPath
    registerField.text = viewModel.getText(indexPath: indexPath)
    let txt = cell.txtfield as UITextField
    txt.delegate = self
    cell.configureCell(registerField)
    return cell
}

并配置单元格

func configureCell(_ fieldData: RegisterFields) {
    txtfield.placeholder = fieldData.placeholderText
    txtfield.isSecureTextEntry = fieldData.isSecureEntry
    txtfield.text = fieldData.text
    txtfield.tag = fieldData.indexPath.item
    imgIcon.image  = fieldData.image
    imgDropDown.isHidden = !fieldData.isDropDown
}

我想将 Rx 用于用户输入,而不是像下一行那样使用委托模式

txt.delegate = 自我

以下是我的屏幕图像

【问题讨论】:

  • 我已经添加了所有关于问题的详细信息,请在投票前阅读问题,谢谢
  • 您是将表格数据绑定到表格视图还是使用普通的表格视图委托?还是 RxDataSource?
  • 我使用的是普通的 tableview 委托,单元格中有一个文本字段,我想在该文本字段中收听用户输入
  • 如果您可以重新打开您的问题,我有您正在寻找的答案
  • @ArslanAsim 现在看到您的问题并认为可以重新打开它的人可以/将投票重新打开它,就像我刚才所做的那样。但它总共需要五个用户,所以你可能需要再等一会儿。

标签: ios swift rx-swift


【解决方案1】:

首先为您的自定义单元格提供其自己的处理包以用于处理分配目的

import RxSwift

class YourCustomCell: UITableViewCell {

   var disposeBag = DisposeBag()

   @IBOutlet weak var textfield: UITextField!

    override func prepareForReuse() {
        super.prepareForReuse()

        disposeBag = DisposeBag()
    }
}

然后在你的控制器中,监听文本字段输入流:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      guard let cell = cell as? YourCustomCell, textfield = cell.textfield else { return }

      textfield
            .rx.textInput.text.orEmpty
            .asDriver()
            .drive(onNext: { [unowned self] text in
               //do what you want here
            })
            .addDisposableTo(cell.disposeBag)
    }

【讨论】:

  • 这样绑定可以吗:cell?.elementTextField?.rx.text .map{$0 ?? ""} .bind(onNext: { [weak self](text) in //do you want here }).disposed(by: self.disposeBag)
  • @TibinThomas 您应该使用驱动程序,因为它会强制使用主线程。鉴于文本字段是一个 UI 元素,您希望在主线程上处理与其相关的事件。驱动程序不能出错,观察主调度程序并共享副作用。在处理用户界面时,您想要什么。
  • 给一个单元它自己的一次性袋子有助于防止一个属性由于 UITableView 的单元重用而被多次订阅,这反过来又避免了 RxSwift 应用程序中的意外行为。
猜你喜欢
  • 2019-06-15
  • 1970-01-01
  • 2015-10-13
  • 2021-03-15
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多