如何格式化文本字段以便当用户输入数据时其格式类似于 80/150?

How to format a textfield so when user inputs data its in format similar to 80/150?

目前有一个文本字段,在用户输入数据后,它必须 post 以类似于 60/500 的格式发送到服务器,所以基本上是一个分数。我熟悉设置文本字段并通过故事板连接它以及设置文本输入特征以便显示数字键盘。我只是不确定如何将输入的文本字段更改为“30/90”分数格式并 posting 它。任何帮助将不胜感激!

您可以这样做,在将 self 设置为委托后:

let slash = "/"
let digits = CharacterSet(charactersIn: "0123456789")

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

    //Deleting
    if string.count == 0 {
        var text = textField.text!
        let start = text.startIndex
        let beginRange = text.index(start, offsetBy: range.location)
        let endRange = text.index(start, offsetBy: range.location + range.length)
        text = String(text.prefix(upTo: beginRange))
            + String(text.suffix(from: endRange))
        text = text.replacingOccurrences(of: "/", with: "")
        if text.count >= 3 {
            text = String(text.prefix(2)) + "/" + String(text.dropFirst(2))
        }

        textField.text = text

        return false
    }

    //Typing

    let count = textField.text!.count
    guard string.count == 1,
        count < 6,
        let scalar = Character(string).unicodeScalars.first else {
            return false
    }

    let isDigit = digits.contains(scalar)

    switch count {
    case 0, 3..<6 :
        return isDigit
    case 1:
        if isDigit {
            textField.text = textField.text! + string + "/"
        }
        return false
    case 2:
        if string == slash {
            return true
        } else {
            textField.text = textField.text! + "/" + string
            return false
        }
    default:
        return false
    }
}

此代码也适用于默认键盘,而不仅仅是数字键盘。