尝试从控制器更改该单元格中的UITextField时,UICollectionView中的单元格返回nil

时间:2019-02-12 16:21:41

标签: ios swift uicollectionview uicollectionviewcell

我有一个带有datePicker的UICollectionViewController。日期更改后,它将调用此函数:

var cell: InfoSection?

@objc func didChangeDate(sender: UIDatePicker) {
    let myDateFormatter: DateFormatter = DateFormatter()
    myDateFormatter.dateFormat = "MM/dd/yyyy hh:mm"

    let mySelectedDate: String = myDateFormatter.string(from: sender.date)
    cell?.dateTextField.text! = mySelectedDate as String
    print("mySelected Date is: ", mySelectedDate as String)
    print("The content of dateTextField is: ", cell?.dateTextField.text!)
}

InfoSection是我的包含textField的单元格。

该单元格在此行显示为零:

cell?.dateTextField.text! = mySelectedDate as String

我确定这里有一个相当明显的解决方案,我很想念。我试过用力拆开它-它崩溃了。我尝试将变量单元格设置为= InfoSection()的值-它在“ dateTextField的上下文”语句中打印日期,但不更改textField。

有一些SO答案说可以通过cellForItemAt indexPath来更改单元格中的数据,但是我不知道如何cell?.dateTextField.text! = mySelectedDate as String时在cellForItemAt中调用func didChangeDate }。

任何帮助都将是惊人的!如果您需要其他任何信息,请告诉我,谢谢!

1 个答案:

答案 0 :(得分:0)

您应将选择的日期存储为变量,并以这种方式重新加载collectionView:

var mySelectedDate: String?

@objc func didChangeDate(sender: UIDatePicker) {
    let myDateFormatter: DateFormatter = DateFormatter()
    myDateFormatter.dateFormat = "MM/dd/yyyy hh:mm"

    mySelectedDate = myDateFormatter.string(from: sender.date)
    collectionView.reloadData()
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellIdentifier", for: indexPath) as! InfoSection

    cell.dateTextField.text = mySelectedDate
    return cell
}