Apple's Implementing Modern Collection Views has an example of implementing custom UICollectionViewCell in Modern Collection Views/Cell Configurations. It demonstrates how to add custom views to UICollectionViewCell.
What I want is it's a UITextField cell. So I added a UITextField and the code was:
class CustomConfigurationCell: UICollectionViewListCell {
// Trying to gain access to UITextField
// But contentView is not a CustomContentView
var textField: UITextField? {
guard let contentView = contentView as? CustomContentView else {
return nil
}
return contentView.textField
}
override func updateConfiguration(using state: UICellConfigurationState) {
var content = CustomContentConfiguration().updated(for: state)
content.name = name
contentConfiguration = content
}
}
struct CustomContentConfiguration: UIContentConfiguration, Hashable {
func makeContentView() -> UIView & UIContentView {
return CustomContentView(configuration: self)
}
}
class CustomContentView: UIView, UIContentView {
public let textField = UITextField();
}
In my UIViewController:
let textFieldCellRegistration = UICollectionView.CellRegistration<CustomConfigurationCell, Key> { (cell, indexPath, item) in
cell.textField?.delegate = self
}
The text field showed up as expected. But unfortunately, cell.textField was nil. I couldn't retrieve user input without UITextViewDelegate.
So how can I implement a text field cell with content configuration?