2017-07-28 114 views
-1

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

例如:如果我在textField键入“红色”,文本的颜色会变为红色。

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

谢谢!

+1

你尝试过什么到目前为止?你的代码是什么样的? – ZGski

+0

@ZGski我只创建了一个文本框和连接插座的基本布局。困惑于如何接近它。 – iVvaibhav

+1

老实说,我认为如果你自己给自己一个机会并且自己测试一下,那么这对大家都有好处。堆栈溢出意味着更多的调试或当你绝对难住 - 而不是要求诸如“我应该如何做这件事”。 – ZGski

回答

0

作为一个起点,你需要创建一个String映射UIColor

let colorMapping: [String: UIColor] = [ 
    "green": .green, 
    "white": .white, 
    //etc... 
] 
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 

} 
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 
] 
0

所以假设你有文本框和TextView的出口或程序创建的颜色的简单集合: -

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 
}