使用UITextFieldDelegate和自定义输入容器

时间:2017-03-12 11:41:59

标签: swift3 uitextfielddelegate

在我当前的应用程序中,我创建了一个自定义输入容器,供用户输入注释。请参考下图。

enter image description here

将textfield设置为UITextFieldDelegate的委托,我想使用shouldChangeCharactersInRange,如果textField为空,则sendButton为灰色,当填充至少1个字符时,它将更改为蓝色。但是,目前使用我的代码,sendButton开始时为蓝色,输入1个字符时变为灰色,然后当字符大于1时变为蓝色。有点奇怪,试图找出原因。这是我目前的相关代码:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField.text?.characters.count)! > 0 {
        sendButton.setTitleColor(ovencloudBlueText, for: .normal)
    } else {
        sendButton.setTitleColor(newLoginGrayText, for: .normal)
    }
    return true
}

我知道这可能是我想念的简单事情。如果这是可能的重复,请告诉我,我会在查看参考链接后删除这篇文章。非常感谢您的投入。

1 个答案:

答案 0 :(得分:3)

这是因为在更新ui 之前触发了shouldChangeCharactersIn 。所以它从蓝色开始'因为textfield是空的。当您输入第一个字符时,shouldChangeCharactersIn有效,但如果您此时检查textField.text?.characters.count,则会看到0sendButton.setTitleColor(newLoginGrayText, for: .normal)有效。当您输入第二个字符时,textField.text?.characters.count1,然后变为蓝色。你可以做你想做的事情;

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

        let  char = string.cString(using: String.Encoding.utf8)!
        let isBackSpace = strcmp(char, "\\b")

        if (isBackSpace == -92) {
            print("Backspace was pressed")
        }

        if (textField.text?.characters.count)! == 0 {
          sendButton.setTitleColor(ovencloudBlueText, for: .normal)
        }
        else if (textField.text?.characters.count)! == 1 && isBackSpace == -92 {
          sendButton.setTitleColor(newLoginGrayText, for: .normal)
        }

    return true
}

你会看到它有效