2017-07-28 119 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 
}