当我将它与视图控制器一起使用时,下面的代码工作正常,尽管我当前的视图控制器有一个标题和文本字段在它们中,并且它不会在代码中出现错误,尽管它没有效果;该函数永远不会被调用?
这是代码 - 首先将func放在类ProfileEditor
中class ProfileEditor: UICollectionViewController, UICollectionViewDelegateFlowLayout, ProfileEditorHeaderDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("text field func called")
let currentCharacterCount = textField.text?.characters.count ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
var maxLength = 0
if textField.isEqual(header.displayNameTextFeild) {
maxLength = 13
return newLength <= maxLength
}
然后我把func放在委托
中 protocol ProfileEditorHeaderDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
}
class ProfileHeaderEditor: UICollectionViewCell {
let displayNameTextField: UITextField = {
let tf = UITextField()
tf.placeholder = "Display name"
tf.font?.withSize(10)
tf.backgroundColor = UIColor.white
tf.textColor = UIColor.black
tf.borderStyle = .roundedRect
return tf
}()
}
答案 0 :(得分:0)
首先,您应该实现UITextFieldDelegate
,其中包含方法:func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
在您创建Cell
profileHeaderEditor.displayNameTextField.delegate = self // add this