2

ユーザーに入力するように指示する文をユーザーが入力することが期待される UITextField があります。したがって、入力する文はすでにわかっています。文の途中で、ユーザーは密かにメッセージを渡す必要があります。これを行う方法は、既知の文の数文字を入力し、「&」を入力してから、WhichEverMessageUserWantsToPass と「&」を入力して終了することです。

キャッチは、ユーザーが「&」を押した瞬間です。その後に入力したものは表示されるべきではありません。代わりに、その後に入力した各文字は、既知の文の文字に置き換えられる必要があります。

例えば:

文字列 - 2 年前に住んでいた都市は?

ユーザーの種類 - どの都市のディ&デテロイト&n 2 年

UITextField が表示されます - 私が 2 年間住んでいた都市はどれですか

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 に置き換えます

そして、テキストフィールドに表示されるテキスト " my ghj sti ui to .." (太字のテキストは実際の質問から読み取られたもので、入力の &X& セクションと一致します)。

:swift 1 の場合は[]をに置き換えnilます。

于 2015-07-19T15:36:09.363 に答える