【问题标题】:Appending a Character to a textField while typing键入时将字符附加到文本字段
【发布时间】:2016-05-13 10:41:00
【问题描述】:

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

【问题讨论】:

  • 究竟想要达到什么目标?
  • @luk2302 我希望在用户在文本字段中输入时将问号附加到用户正在输入的字符串的末尾。我也需要禁用一个按钮,只要 textField 为空并且需要限制和显示字符数。

标签: ios swift swift2 uitextfield


【解决方案1】:

线索在您正在实现的委托方法的名称中:shouldReplaceCharactersInRange

您正在覆盖它,就好像它是 didReplaceCharactersInRange

在您从此方法返回之后,如果有的话,字符的替换不会发生(取决于返回值)。

如果你想在这个方法中自己修改文本,你应该从方法中返回false

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

您当前在 textField 的文本中附加一个问号,但不要添加用户尝试输入的字符。

你可能想让它更像:

textField.text! = text + '?'

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

【讨论】:

  • 感谢您的回答@MatthewHallatt。我实现的方法实际上称为shouldChangeCharactersInRange 如果我从该方法返回false,每个键入的字符都被替换为“?”
  • 检查我的编辑 - 我可能解释得不够好
【解决方案2】:

这就是我的诀窍:

@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

            }
        }
    }

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 2016-05-11
    • 1970-01-01
    • 2011-12-27
    • 2015-09-05
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多