somejonus somejonus - 5 months ago 15
iOS Question

Appending a Character to a textField while typing

The textField is supposed to do the following:

User types "w" -> textField: "w?"
User types "ho are you" -> textfield: "who are you?


Right now for every character that is typed a "?" is added before it.

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

let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
let newLength = text.characters.count

if newLength <= 25 {
cLabel.text = String(25 - newLength)
if text.isEmpty { //Checking if the input field is not empty
ahskButton.userInteractionEnabled = false //Disabling the button
ahskButton.enabled = false

} else {
ahskButton.userInteractionEnabled = true //Enabling the button
ahskButton.enabled = true
textField.text! += "?" //NOT WORKING
}

return true;
} else {
return false;
}
}

Answer

Here is what did the Trick for me:

@IBAction func textEdit(sender: UITextField) {

        let quest:Character = "?" // Character to append

        if sender.text!.characters.count == 1 { // if textfield has exactly one character

            if sender.text! != "?" { // if this character is not "?"

                self.ahskField.text!.append(quest) // append "?"

                // the following repositions the cursor in front of the "?"

                // only if there is a currently selected range
                if let selectedRange = sender.selectedTextRange {

                // and only if the new position is valid
                if let newPosition = sender.positionFromPosition(selectedRange.start, inDirection: UITextLayoutDirection.Left, offset: 1) {

                // set the new position
                sender.selectedTextRange = sender.textRangeFromPosition(newPosition, toPosition: newPosition)
                    }
                }

            } else {

                sender.text = "" //Clear TextField

                cLabel.text = "25" //Reset textcount Label

            }
        }
    }