首页 > 解决方案 > 试图限制 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
}

我希望能够将单个文本字段限制为不同的数字。在界面构建中有一个可以输入的部分来限制这一点。但是此错误不断弹出:“无法调用非函数类型的值String,在描述的部分中:

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

标签: iosswiftuitextfield

解决方案


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

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

我创建了一个 github 存储库,用于在此处测试此代码:Github Repository

首先,确保在界面生成器中将Keyboard Type两者UITextField的 s设置为。Number Pad

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

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 = "$00.00"
            case 1:
                textField.text = "$00.0\(newText!)"

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

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

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

            default:
                break
            }
            return false
        }
    }
}

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

最终结果:

在此处输入图像描述

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


推荐阅读