2017-07-28 21 views
-1

私はUITextViewを持っており、ユーザーが入力した色になるStringを検出する必要があります。次に、UITextFieldのテキストの色を、ユーザーが入力した色に変更する必要があります。テキストの色をUITextFieldの色に変更します

たとえば、textFieldに「赤」と入力すると、テキストの色が赤に変わります。

これはどのように行うことができますか?

ありがとうございます!

+1

は、あなたがこれまで何を試してみましたか?あなたのコードはどのように見えますか? – ZGski

+0

@ZGski私は、テキストフィールドとそれに接続されたアウトレットの基本レイアウトを作成しました。それにアプローチする方法については混乱しています。 – iVvaibhav

+1

正直なところ、あなたがたぶん自分で打撃を与え、あなた自身でテストしたことがあれば、皆にとって有益だと思います。スタックオーバーフローは、デバッグや、まったく困惑しているときのためのものです。 – ZGski

答えて

0

StringUIColorのマッピングを作成する必要があります。その適切なUIColorに各色のテキストをマッピングすることにより

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

スタート:

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 
} 
関連する問題