当文本与文本字段大小相同时,如何停止在文本字段中输入字符?

How to stop typing characters in textfield when text is the same size as textfield?

我想找到一种方法,当字符完全填满文本字段时,让用户键入但不向文本字段添加任何新字符(如 Snapchat)。我只在 Objective-C 中看到过此操作,但无法将其翻译成 Swift。有人可以帮忙吗?谢谢!

你可以这样做:

@IBAction func textField_EditingChanged(sender: AnyObject) {
            //Set your font and add attributes if needed.
            let stringSize: CGSize = textField!.text!.sizeWithAttributes([NSFontAttributeName: textField.font!])

            if (stringSize.width > textField.bounds.width - 20){
                textField.deleteBackward()
            }
    }

我添加了 - 20,因为我想确保没有添加小字符,例如 "i"、“1”等