在键入时将字符附加到textField

时间:2016-05-13 10:41:00

标签: ios swift swift2 uitextfield

textField应该执行以下操作:

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

现在为每个键入“?”的角色在它之前添加。

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;
        }
    }

2 个答案:

答案 0 :(得分:0)

线索是您正在实施的委托方法的名称:shouldReplaceCharactersInRange

您将其覆盖为didReplaceCharactersInRange

直到之后从此方法返回时才会替换字符(如果有的话)(取决于返回值)。

如果您想在此方法中自行更改文本,则应从方法返回false

编辑: 如果您返回false,则文本不会自动更改。

您目前使用问号附加textField文本,但不要添加用户尝试输入的字符。

你可能想让它更像:

textField.text! = text + '?'

基本上,每次调用此方法时,您都希望手动将textField的文本设置为正确的字符串。

答案 1 :(得分:0)

以下是对我的伎俩:

@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

            }
        }
    }