试图限制 maxTextFieldLength

Trying to limit maxTextFieldLength

我正在编写一个需要输入数量和价格的应用程序,我想将数量限制为 4 位数字,将价格限制为 4 位数字,并在 4 位数字之间保留小数。

如何将其编码到我的项目中?

我搜索了多个页面并发现了这个:(http://www.globalnerdy.com/2016/05/24/a-better-way-to-program-ios-text-fields-that-have-maximum-lengths-and-accept-or-reject-specific-characters/)我在 TextFieldMaxLength.Swift 文件的代码末尾仍然不断收到错误消息。

@objc func limitLength(textField: UITextField) {
    guard let prospectiveText = textField.text, prospectiveText.count > maxLength else {
            return
    }

    // If the change in the text field's contents will exceed its maximum length,
    // allow only the first [maxLength] characters of the resulting text.
    let selection = selectedTextRange
    text = prospectiveText.substringWith(
        Range<String.Index>(prospectiveText.startIndex ..< prospectiveText(maxLength))
    )
    selectedTextRange = selection
}

我希望能够将各个文本字段限制为不同的数字。在界面建筑中有一个可以输入的部分来限制这一点。但是这个错误不断弹出:"Cannot call value of non-function type String",在描述的部分中:

text = prospectiveText.substringWith(
            Range<String.Index>(prospectiveText.startIndex ..< prospectiveText(maxLength))
        )

你应该做的是实现 UITextFieldDelegate 方法 textField(_:shouldChangeCharactersIn:replacementString:)

此委托方法在 UITextField 中的文本更新之前调用。在其中,您可以检查当前字符串的长度,如果当前长度为 4 个字符并且添加的字符不是退格符,则 return false,否则 true。同样,您可以更改 textField 的文本和 return false,有效地处理更新字符,并 returning 适当的字符串。

我创建了一个 github 存储库,我用它来测试这里的代码:Github Repository

首先,确保在界面生成器中将两个 UITextFieldKeyboard Type 设置为 Number Pad

接下来,将以下扩展名添加到字符串 class。

extension String {
    func stringByRemovingAll(characters: [Character]) -> String {
        var stringToReturn = self
        for character in characters {
            stringToReturn = stringToReturn.replacingOccurrences(of: String(character), with: "")
        }
        return stringToReturn
    }

    subscript (i: Int) -> Character {
        return self[index(startIndex, offsetBy: i)]
    }
}

现在,真正解决这个问题:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var volumeTextField: UITextField!
    @IBOutlet var priceTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        volumeTextField.delegate = self
        priceTextField.delegate = self
    }
}


extension ViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        //An empty string, i.e. "", is the passed text when the user enters a backspace
        if textField == volumeTextField {

            if textField.text!.count == 4 && string != "" {
                return false
            } else {
                return true
            }
        } else {

            let currentText = textField.text!.stringByRemovingAll(characters: ["$","."])
            print(currentText)

            var newText: String!
            if string == "" {
                newText = String(currentText.dropLast())
            } else if currentText.count == 0 {
                newText = string
            } else {
                newText = "\(currentText)\(string)"
            }


            while newText.count != 0 && newText[0] == "0" {
                newText.remove(at: newText.startIndex)
            }

            switch newText.count {

            case 0:
                textField.text = "[=11=].00"
            case 1:
                textField.text = "[=11=].0\(newText!)"

            case 2:
                textField.text = "[=11=].\(newText[0])\(newText[1])"

            case 3:
                textField.text = "[=11=]\(newText[0]).\(newText[1])\(newText[2])"

            case 4:
                textField.text = "$\(newText[0])\(newText[1]).\(newText[2])\(newText[3])"

            default:
                break
            }
            return false
        }
    }
}

在此委托方法中,您还可以检查传递的字符,并且 return false 如果它不是您希望允许的少数字符之一。

最终结果:

参考: Apple docs textField(_:shouldChangeCharactersIn:replacementString:) reference