【问题标题】:my Callback in CollectionViewCell doesn't work correctly我在 CollectionViewCell 中的回调无法正常工作
【发布时间】:2020-02-12 08:09:03
【问题描述】:

我有一个带有 PhoneNumberTextField 的简单 CollectionViewCell 和一个我想发送到我的服务器的回调

class PhoneNumberCollectionViewCell: UICollectionViewCell, NiBLoadable, UITextFieldDelegate {



@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var PhoneNumberTextField: UITextField!
@IBOutlet weak var SecurityLabel: UILabel!

var returnValue: ((_ value: String) -> ())?

override func awakeFromNib() {
    super.awakeFromNib()
    Decorator.decorate(self)

}

func setPhoneLabelText(text: String) {
    phoneLabel.text = text
}

func setSecurityLabel(text: String) {
    SecurityLabel.text = text
}

func textFieldDidEndEditing(_ textField: UITextField) {
    returnValue?(PhoneNumberTextField.text ?? "") // Use callback to return data
}

}

我也有我的 ViewController 和我的 CollectionView,我无法将我的 phoneNumber 从单元格获取到 ViewController 中的变量。代码来了

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let models = model[indexPath.row]

    switch models {
    case .phoneNumber:
        if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhoneNumberCollectionViewCell.name, for: indexPath) as? PhoneNumberCollectionViewCell {

            cell.setSecurityLabel(text: "_ALLYOURDATAISINSECUREDAREA")
            cell.setPhoneLabelText(text: "_YOURPHONENUMBER")
            cell.PhoneNumberTextField.text = phoneNumber

            cell.returnValue = { value in
                self.phoneNumber = value
            }
            return cell
        }

当我打印从 textField 得到的内容时,我得到了 nil

   @objc func sendPhoneNumber() {     
    print("PHONE NUMBER IS - \(String(describing: self.phoneNumber))")
}

我在做什么错???

【问题讨论】:

  • 您是否设置了textfield 委托?

标签: swift callback closures tableview


【解决方案1】:

您需要为 textField 设置委托,否则 textField 委托将不起作用。

override func awakeFromNib() {
    super.awakeFromNib()
    Decorator.decorate(self)
    PhoneNumberTextField.delegate = self
}

旁注: 不要大写变量和常量。

编辑第二个问题: 您要么想要(通过 Xib)创建一个在值更改时调用的 IBAction 出口,要么:

textField.addTarget(self, action: #selector(textFieldValueChanged), for: .editingChanged)

每次输入或删除字母时,这两个选项都会调用委托函数。

【讨论】:

  • 谢谢!但现在我遇到了另一个问题。我应该总是点击调用函数 textFieldDidEndEditing!没有这个水龙头我还有其他方法吗??)))
  • 你的意思是你必须在textFieldDidEndEditing触发之前改变目标?
  • 为你编辑了答案。
【解决方案2】:

您是否注册了集合视图单元并声明了委托和数据源?

 let flowLayout = UICollectionViewFlowLayout()

 let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
 collectionView(PhoneNumberCollectionViewCell.self, forCellWithReuseIdentifier: PhoneNumberCollectionViewCell.name)
 collectionView.delegate = self
 collectionView.dataSource = self

 return collectionView

【讨论】:

  • 与collectionView无关datasource,textfield委托要设置在UICollectionViewCell
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多