限制UITextField上的字符会破坏Emojis,只能添加一个而不能删除

时间:2016-02-22 05:57:34

标签: ios uitextfielddelegate

我正在使用以下代码来限制UITextField中可以包含的字符数

public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

        let currentCharacterCount = textField.text?.characters.count ?? 0
        if (range.length + range.location > currentCharacterCount){
            return false
        }
        let newLength = currentCharacterCount + string.characters.count - range.length
        return newLength <= 44
    }

这是通过将UITextField的委托设置为self来完成的。

-

这里的问题是,如果您在文本字段中添加表情符号,则无法将其删除。即使你突出显示 - 选择全部,或使用“剪切”,文本也不会改变。表情符号可以在文本之前或之后,甚至可以在文本字段中单独使用。您也无法在该字段中添加两个表情符号。

我不知道这里有什么问题,任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

如果你不在shouldChange ..函数内进行任何检查,它会更好,而是使用UITextFieldTextDidChangeNotification通知单独跟踪长度。示例代码如下。在shouldChange..just返回一个在textDidChange中设置的bool。在这里,您将获得正确的长度。我注意到,在你的方法中,一旦添加表情符号,它甚至不允许你再输入。在输入表情符号字符后,甚至没有调用shouldChangeCharactersInRange。

class ViewController: UIViewController, UITextFieldDelegate{

    @IBOutlet weak var textField:UITextField!
    var allow = true

    override func viewDidLoad() {
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldDidChange:", name: UITextFieldTextDidChangeNotification, object: textField)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

     func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        return allow
    }

    func textFieldDidChange(notification:NSNotification)
    {
        let length = textField.text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
        if length > 44 {
            allow = false
        } else {
            allow = true
        }
    }

}

答案 1 :(得分:0)

在Swift 3.1中

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentCharacterCount = textField.text?.characters.count ?? 0
    let limit = 10
    return currentCharacterCount < limit || string.characters.count < range.length
}

这不会阻止复制和粘贴长文本字符串,我禁用了UITextField的粘贴功能,代码来自

https://stackoverflow.com/a/39015132/6311644