在 UITextField 中的每种类型后替换字符?

Replacing character after each type in UITextField?

我有一个 UITextField,希望用户在其中键入我们告诉用户键入的句子。所以我们已经知道 to type 的句子。话说到一半,用户要偷偷传一条消息。执行此操作的方法是键入已知句子的几个字母,然后键入“&”,然后键入 WhichEverMessageUserWantsToPass 和“&”结束。

关键在于用户按下“&”的那一刻,他之后键入的任何内容都不应显示,而是他之后键入的每个字母都应替换为已知句子中的字母。

例如:

String - Which city did I live in 2 years ago?

User types - Which city di&Deteroit&n 2 yea

UITextField should show - Which city did I live in 2 yea

两个“&”之间的部分本身就是答案,所以我不希望它显示在文本字段中。

我目前的做法是:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
    var addString = String(self.character[self.textLength])
    
    var start = textField.text.endIndex // Start at the string's end index as I only want the most recent character to be replaced
    var end = textField.text.endIndex // Take the string's end index as I only want one character to be changes per type
    var nextRange: Range<String.Index> = Range<String.Index>(start: start,end: end)
    
    textField.text.stringByReplacingCharactersInRange(nextRange, withString: addString)
    
    
    return true
}

然而,这似乎并没有取代目前的任何字母。如果有人知道实现,请提供帮助。谢谢

好了 - 试试吧!

let initialString = "my question to be answered"
var inputString = NSString()

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    inputString = inputString.stringByReplacingCharactersInRange(range, withString: string)

    textField.text = inputString as String
    var range = Range<String.Index>(start: (textField.text?.startIndex)!,end: (textField.text?.endIndex)!)

    while true {
        if let firstIndex = textField.text!.rangeOfString("&", options: [], range: range, locale: nil) {
            range = Range<String.Index>(start: firstIndex.startIndex.successor(), end: (textField.text?.endIndex)!)
            var endIndex : String.Index?
            if let index = textField.text!.rangeOfString("&", options: [], range: range, locale: nil) {
                endIndex = index.endIndex
                range = Range<String.Index>(start: index.startIndex.successor(), end: (textField.text?.endIndex)!)
            } else {
                endIndex = textField.text?.endIndex
            }

            let relevantRange = Range(start: firstIndex.startIndex,end: endIndex!)
            let repl = initialString.substringWithRange(relevantRange)

            print("would replace the \(relevantRange) with \(repl)")

            textField.text!.replaceRange(relevantRange, with: repl)
        } else {
            break
        }
    }
    return false
}

我认为这正是您想要的 加上 非常干净,您可以删除或添加 & 中间句子,一切都按预期工作。

"&X&ghj&X&ui&X&.." 输入的示例输出为

would replace the 0..<3 with my
would replace the 6..<9 with sti
would replace the 11..<14 with to

文本字段中显示的文本“my ghjstiui to.."(粗体文本是从实际问题中读取的文本,与输入的 &X& 部分匹配。)

注意:对于swift 1 将[]替换为nil