2

我有一个 UITextField ,用户应该在其中输入一个我们告诉用户输入的句子。所以我们已经知道要输入的句子。在句子的中间,用户必须秘密传递一条消息。执行此操作的方法是键入已知句子的几个字母,然后键入“&”,然后键入“WhichEverMessageUserWantsToPass”和“&”结束。

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

例如:

String - 两年前我住在哪个城市?

用户类型 - 哪个城市 di&Deteroi&n 2 yea

UITextField 应该显示 - 我在 2 年住在哪个城市

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

我目前的做法是:

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
}

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

4

1 回答 1

3

你去 - 试试吧!

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&.."将是

将 0..<3
替换为 my 将 6..<9
替换为 sti 将 11..<14 替换为 to

And the text displayed in the text-field "my ghjstiui to.." (the bold text is the one being read from the actual question and matches the &X& sections of the input.)

Note: for swift 1 replace the [] with nil.

于 2015-07-19T15:36:09.363 回答