2017-09-06 17 views
-2

Swift 4 iOS-UITextFieldを使用して「単語数」機能を作成しようとしています。次のコードは、私のUITextFieldの中に入力された文字列のために.countを印刷することができません。Swift 4 iOS - UITextFieldからの単語数

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
    super.viewDidLoad() 

     //INPUT BOX - for Word Count! 
     let INPUT : UITextField = UITextField(frame: CGRect(x: 35, y: 200, width: 350, height:50)) 
      INPUT.placeholder = "Type Words separated with Spaces!" 
      INPUT.font = UIFont.init(name:"times", size: 22) 
      INPUT.backgroundColor = UIColor(red:0x00 ,green:0xff, blue:0x00 ,alpha:1) 
      self.view.addSubview(INPUT) 

     //variable holding the value of text typed 
     let strings : String! = INPUT.text 

     //variable holding the methods for detecting spaces and new lines 
     let spaces = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) 

     //variable storing the amount of words minus the spaces 
     let words = strings.components(separatedBy: spaces) 

     //method to display the word count in the console 
     print(words.count) 
    } 
} 

このエラーがコンソールに印刷されている:あなたのTextViewには、その時点で、それには内容がないためです0

+0

何が起こるのでしょうか?そこにエラーがあるか、またはカウントが0ですか? – Adarkas2302

+0

このエラーはコンソールに出力されています: "Result" =>:0 – ctaylorgraphics

+0

これは正しいです。私はあなたのコードを試して、私の答えを追加しました。その後、2を表示します。 –

答えて

1

: 「結果」=>を。

これを試してみてください:

INPUT.text = "Some Text" 

は、実際の入力からテキストを取得実行します。

INPUT.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) 

func textFieldDidChange(_ textField: UITextField) { 

    let strings : String! = INPUT.text 
    let spaces = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) 
    let words = strings.components(separatedBy: spaces) 
    print(words.count) 

} 
+0

Jonas、この問題は、ユーザーがUITextFieldに入力するときにテキストを検出することです。現在、.countプロパティは、UITextFieldの中に入力した後、INPUT.textから分離された文字列値の整数値を検出しません。あなたの助けと提案に感謝します。 – ctaylorgraphics

+0

それからあなたがそれを読もうとする位置を示してください。あなたのコード例では何も表示されないので何も表示されません –

+0

@ctaylorgraphicsすべてのコードは 'viewDidLoad'に残っています。単語カウントを出力する 'UITextFieldDelegate'メソッドはありますか? – sCha

関連する問題