简体   繁体   English

限制 UITextField 中的字符? - 斯威夫特/Xcode

[英]Limiting Characters in UITextField? - Swift/Xcode

I'm new to developing and I am trying to limit the number of characters that can be entered in a textfield, with the most recent version of Swift.我是开发新手,我正在尝试使用最新版本的 Swift 限制可以在文本字段中输入的字符数。 I have tried to follow several different tutorials and have checked out a few different answers around the site, but I am not having much luck.我尝试遵循几个不同的教程,并在网站上查看了一些不同的答案,但我运气不佳。

Currently, I have this entered in my swift file:目前,我已将其输入到我的 swift 文件中:

@IBAction func InfoTextFieldLimit(sender: UITextField) {

        self.InfoTextField.delegate = self

        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 <= 10
        }
    }

...I'm not getting any errors, but nothing seems to be happening when I run the app. ...我没有收到任何错误,但是当我运行该应用程序时似乎没有发生任何事情。

I have also tried at least 3 other methods that I didn't bother copying.我还尝试了至少 3 种其他方法,但我懒得复制。 (but can provide on request) (但可应要求提供)

Can anybody tell me what I'm doing wrong and point me in the right direction?谁能告诉我我做错了什么并指出我正确的方向? Would be much appreciated!将不胜感激! ...I feel like there's a good chance I might be overlooking something that's obvious. ...我觉得我很有可能忽略了一些显而易见的事情。

I am also going to want to do this with a textview down the road, how would that be different?我也想在路上用 textview 来做到这一点,那会有什么不同?

func textField(textField: UITextField, shouldChangeCharactersInRange range:      NSRange, replacementString string: String) -> Bool {
    let maxLength = 50
    guard let text = textField.text else { return true }     
    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= maxLength
}

Also make sure you have set the delegate of the UITextField to the UIViewController还要确保您已将UITextField的委托设置为UIViewController

I originally had this code in objective-c:我最初在objective-c中有这个代码:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 4) ? NO : YES;
}

I tried converting it to swift, let me know if it works... You have to use the UITextFieldDelegate method.我尝试将它转换为 swift,让我知道它是否有效......你必须使用 UITextFieldDelegate 方法。

func textField( textField:UITextField,shouldChangeCharactersInRange range:NSRange,replacementString string:NSString)->Bool{
var newLength:NSUInteger = textField.text.length + string.length  - range.length 

return null(newLength >  4 )?false:true

}

Just in case, don't forget to guard range size before applying it to the string. 以防万一,在将其应用于字符串之前,请不要忘记保护范围大小。 Otherwise, you will get crash if the user will do this: 否则,如果用户执行此操作,则会崩溃:

Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size) 键入最大长度的文本插入内容(由于长度限制,将不会插入任何内容,但iOS对此一无所知)撤消插入操作(发生崩溃,原因是范围大于实际的字符串大小)

Also, using iOS 13 users can accidentally trigger this by gestures 此外,使用iOS 13用户可能会通过手势意外触发此操作

I suggest you add to your project this 我建议您将此添加到您的项目中

extension String {
    func replace(with text: String, in range: NSRange) -> String? {
        guard range.location + range.length <= self.count else { return nil }
        return (self as NSString).replacingCharacters(in: range, with: text)
    }
}

And use it like this: 并像这样使用它:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard let newText = textView.text.replace(with: text, in: range) else { return false }
    return newText.count < maxNumberOfCharacters
}

Otherwise, you will constantly be getting crashed in your app 否则,您将不断崩溃于应用程序中

maxNumberOfCharacters - your constant or @IBInspectable variable maxNumberOfCharacters-您的常量或@IBInspectable变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 斯威夫特3 | Xcode 8 datePicker更新UItextField - Swift 3 | Xcode 8 datePicker update UItextField 在CollectionViewCell中输入UITextField(swift 3 xcode) - Input of UITextField in CollectionViewCell (swift 3 xcode) Swift 3:显示UITextField中剩余的字符 - Swift 3: Show characters remaining in UITextField 使UITextField分析键入的单个字符,而不是Xcode Swift中的整个字符? - Making the UITextField analyze individual characters typed in rather than as a whole in Xcode Swift? 限制UITextField上的字符会破坏Emojis,只能添加一个而不能删除 - Limiting characters on UITextField breaks Emojis, can only add one and not delete 将用户在UITextField中的输入限制为一定范围的数字(而不是字符数) - Limiting user input in a UITextField to a certain range of numbers (not number of characters) UIAlertView Textview中的Xcode iOS限制字符 - Xcode ios Limiting characters in UIAlertView Textview 如何在 Swift 中的 UITextField Xcode 中设置光标位置 - How to set position of cursor in UITextField Xcode in Swift UIcollectionViewCell中的UITextField的单个边框(swift 3 xcode) - single border for UITextField within a UIcollectionViewCell (swift 3 xcode) 在Xcode 8和Swift 3中将UITextField转换为Integer并使用它们进行计算 - Convert UITextField to Integer in Xcode 8 and Swift 3 and calculate with them
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM