当我将下面的代码与 View Controller 一起使用时,它可以正常工作,尽管我当前的 View Controller 有一个标题和文本字段,并且它不会在代码中产生错误,尽管它没有任何效果;该函数从未被调用?
这是代码 - 首先将 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 放入委托(delegate)中
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
}()
}
最佳答案
首先,您应该实现 UITextFieldDelegate
,其中包含方法:func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
在创建 Cell
的位置添加此行
profileHeaderEditor.displayNameTextField.delegate = self // add this
关于ios - shouldChangeCharactersIn range 函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47214734/