ios - shouldChangeCharactersIn range 函数未被调用

标签 ios swift uitextfield

当我将下面的代码与 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/

相关文章:

iphone - 内存警告后自定义 UITableView headerView 消失

objective-c - 此 bundle 无效 - 文件扩展名必须是 .zip

ios - UIDatePicker 设置 UITextfield 文本

ios - ios有 overdraw 问题吗

ios - 如何将 subview 添加到父 View 范围之外

ios - 在 Swift 中找不到 ImgurSession 文件

ios - 如何在 swift 中使用 NSUserDefaults 保存标签?

ios - 用户开始编辑后如何将占位符附加到 TextView /文本字段

ios - 更改 uitextfield 的外观

ios - 链接到用户默认值的属性导致应用程序崩溃