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

标签 ios swift uitextfield

我想找到一种方法,当字符完全填满文本字段时,让用户输入但不会向文本字段添加任何新字符(如 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”等这样的小字符。

关于ios - 当文本与文本字段大小相同时,如何停止在文本字段中输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847705/

相关文章:

swift - URL 在 Swift 3 中始终为 nil

ios - 如何在 iOS 上使用 Sign In with Google 修复 `The user canceled the sign-in flow.`?

iphone - UITextField 隐藏键盘但 Reamin First Responder?

ios - UITextField 中的自动布局 : Auto Layout still required after executing -layoutSubviews

uiscrollview - scrollRectToVisible UITextField 不随自动布局滚动

ios - 上传图片到服务器时无法显示进度条

ios - 清除 UIAutomation 测试的钥匙串(keychain)

ios - 如何将图标组织到不同位置(如 iPhone 主屏幕)

swift - 有什么方法可以使 UITextFieldDelegate 在 swift 中更具动态性?

ios - ios 中的应用内购买是否可以使用特定于帐户的订阅?