将文本UITextField的颜色更改为其中键入的颜色

时间:2017-07-28 18:41:41

标签: swift uitextfield uicolor

我有一个UITextView,我需要检测String这将是用户在其中输入的颜色。然后我需要将UITextField中文本的颜色更改为用户键入的颜色。

例如:如果我输入红色'在textField中,文字的颜色应该变为红色。

有谁知道如何做到这一点?

谢谢!

4 个答案:

答案 0 :(得分:0)

首先,您需要创建StringUIColor的映射。

let colorMapping: [String: UIColor] = [
    "green": .green,
    "white": .white,
    //etc...
]

答案 1 :(得分:0)

首先将每种颜色的文本映射到相应的UIColor

let colors: [String: UIColor] = [
    // add any built-in colors
    "red": .red,
    "blue": .blue,
    // custom colors too!
    "goldenrod": UIColor(red: 218, green: 165, blue: 32) 
    // add all the colors you wish to detect
    // ...
    // ...
]

使包含文本字段的视图控制器符合UITextViewDelegate并实现shouldChangeTextIn函数(每当用户输入/删除字符时都会调用):

class MyViewController: UIViewController, UITextFieldDelegate {

    // ... other view controller code

    func textField(_ textField: UITextField, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

        if let currentText = textField.text {
            // check if the text is in the `colors` dictionary
            //   and if so, apply the color to the `textColor`
            if colors.keys.contains(currentText) {
                textField.textColor = colors[currentText]
            }
        }

        return true

    }

    // ... other view controller code

}

答案 2 :(得分:0)

您可以使用以下委托方法

检测文本字段中的文本
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
        //Don't forgot to make user entered content to lowercaseString while checking with colorCollection

        if colorCollection.keys.contains(textField.text.lowercaseString) {
            textField.textColor = colorCollection[currentText] //If entered content match with any colour then it will change the text colour of textfield  
        }

    return true
}

创建简单的颜色集合,如下所示

let colorCollection: [String: UIColor] = [
    "blue": .blue,
    "purple": .purple,
    //your other coolers 
] 

答案 3 :(得分:0)

假设你有textfield和textview outlet或以编程方式创建: -

let textField = UITextField()
let txtVw = UITextView()
 //If enter some text inside textfield for instance red then get the value, compare it and set the text color on textview
if textField.text?.lowercased() == "red" {
 txtVw.textColor = UIColor.red
} 
相关问题