我有一个带有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
。
任何帮助都会很棒!如果您需要任何其他信息,请告诉我,谢谢!
您应该将所选日期存储为变量并以这种方式重新加载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
}