ios 最大长度 UITextField
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25223407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Max length UITextField
提问by Giorgio Nocera
When I've tried How to you set the maximum number of characters that can be entered into a UITextField using swift?, I saw that if I use all 10 characters, I can't erase the character too.
当我尝试如何使用 swift 设置可以输入到 UITextField 的最大字符数时?,我看到如果我使用所有10个字符,我也无法擦除该字符。
The only thing I can do is to cancel the operation (delete all the characters together).
我唯一能做的就是取消操作(一起删除所有字符)。
Does anyone know how to not block the keyboard (so that I can't add other letters/symbols/numbers, but I can use the backspace)?
有谁知道如何不阻塞键盘(这样我就不能添加其他字母/符号/数字,但我可以使用退格键)?
回答by Imanou Petit
With Swift 5 and iOS 12, try the following implementation of textField(_:shouldChangeCharactersIn:replacementString:)
method that is part of the UITextFieldDelegate
protocol:
使用 Swift 5 和 iOS 12,尝试以下textField(_:shouldChangeCharactersIn:replacementString:)
方法的实现,这是UITextFieldDelegate
协议的一部分:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
- The most important part of this code is the conversion from
range
(NSRange
) torangeOfTextToReplace
(Range<String.Index>
). See this video tutorialto understand why this conversion is important. - To make this code work properly, you should also set the
textField
'ssmartInsertDeleteType
value toUITextSmartInsertDeleteType.no
. This will prevent the possible insertion of an (unwanted) extra space when performing a paste operation.
- 这段代码最重要的部分是从
range
(NSRange
) 到rangeOfTextToReplace
(Range<String.Index>
)的转换。请参阅此视频教程以了解为什么这种转换很重要。 - 为了使此代码正常工作,您还应该将
textField
的smartInsertDeleteType
值设置为UITextSmartInsertDeleteType.no
。这将防止在执行粘贴操作时可能插入(不需要的)额外空间。
The complete sample code below shows how to implement textField(_:shouldChangeCharactersIn:replacementString:)
in a UIViewController
:
下面的完整示例代码展示了如何textField(_:shouldChangeCharactersIn:replacementString:)
在 a 中实现UIViewController
:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField! // Link this to a UITextField in Storyboard
override func viewDidLoad() {
super.viewDidLoad()
textField.smartInsertDeleteType = UITextSmartInsertDeleteType.no
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldText = textField.text,
let rangeOfTextToReplace = Range(range, in: textFieldText) else {
return false
}
let substringToReplace = textFieldText[rangeOfTextToReplace]
let count = textFieldText.count - substringToReplace.count + string.count
return count <= 10
}
}
回答by Martin
I do it like this:
我这样做:
func checkMaxLength(textField: UITextField!, maxLength: Int) {
if (countElements(textField.text!) > maxLength) {
textField.deleteBackward()
}
}
The code works for me. But I work with storyboard. In Storyboard I add an action for the text field in the view controller on editing changed.
该代码对我有用。但我使用故事板。在 Storyboard 中,我在编辑 changed 时为视图控制器中的文本字段添加了一个操作。
回答by Shan Ye
Update for Swift 4
Swift 4 更新
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
let newLength = text.count + string.count - range.length
return newLength <= 10
}
回答by Sruit A.Suk
Add More detail from @Martin answer
从@Martin 答案中添加更多详细信息
// linked your button here
@IBAction func mobileTFChanged(sender: AnyObject) {
checkMaxLength(sender as! UITextField, maxLength: 10)
}
// linked your button here
@IBAction func citizenTFChanged(sender: AnyObject) {
checkMaxLength(sender as! UITextField, maxLength: 13)
}
func checkMaxLength(textField: UITextField!, maxLength: Int) {
// swift 1.0
//if (count(textField.text!) > maxLength) {
// textField.deleteBackward()
//}
// swift 2.0
if (textField.text!.characters.count > maxLength) {
textField.deleteBackward()
}
}
回答by Sai kumar Reddy
In Swift 4
在斯威夫特 4
10 Characters limit for text field and allow to delete(backspace)
文本字段的 10 个字符限制并允许删除(退格)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == userNameFTF{
let char = string.cString(using: String.Encoding.utf8)
let isBackSpace = strcmp(char, "\b")
if isBackSpace == -92 {
return true
}
return textField.text!.count <= 9
}
return true
}
回答by Basil Mariano
Swift 3
斯威夫特 3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let nsString = NSString(string: textField.text!)
let newText = nsString.replacingCharacters(in: range, with: string)
return newText.characters.count <= limitCount
}
回答by Jeremy Andrews
func checkMaxLength(textField: UITextField!, maxLength: Int) {
if (textField.text!.characters.count > maxLength) {
textField.deleteBackward()
}
}
a small change for IOS 9
IOS 9 的一个小改动
回答by mohsen
you can extend UITextField and add an @IBInspectable
object for handle it:
您可以扩展 UITextField 并添加一个@IBInspectable
对象来处理它:
SWIFT 5
快速 5
import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
@IBInspectable var maxLength: Int {
get {
guard let l = __maxLengths[self] else {
return 150 // (global default-limit. or just, Int.max)
}
return l
}
set {
__maxLengths[self] = newValue
addTarget(self, action: #selector(fix), for: .editingChanged)
}
}
@objc func fix(textField: UITextField) {
if let t = textField.text {
textField.text = String(t.prefix(maxLength))
}
}
}
and after that define it on attribute inspector
然后在属性检查器上定义它
请参阅Swift 4 原始答案
回答by maxwell
If you want to overwrite the last letter:
如果你想覆盖最后一个字母:
let maxLength = 10
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if range.location > maxLength - 1 {
textField.text?.removeLast()
}
return true
}
回答by frouo
I posted a solution using IBInspectable
, so you can change the max length value both in interface builder or programmatically. Check it out here
我使用 发布了一个解决方案IBInspectable
,因此您可以在界面构建器中或以编程方式更改最大长度值。在这里查看