2017-09-06 30 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) 
    } 
} 

这个错误被印在控制台: “结果” =>:0

+0

是什么情况?有没有错误或计数为0? – Adarkas2302

+0

此错误正在打印在控制台中: “结果”=>:0 – ctaylorgraphics

+0

但是,这是正确的..它应该是0在该位置。我试过你的代码并添加了我的答案。然后它打印2. –

回答

1

那是因为你的TextView有在这一点上它没有文字。

试试这个:

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时检测到文本。目前,在UITextField中键入内容后,.count属性不会检测INPUT.text中分隔字符串值的整数量。感谢您的帮助和建议。 – ctaylorgraphics

+0

然后显示您尝试阅读的位置。在你的代码示例中,它不能打印任何东西,因为它没有任何东西 –

+0

@ctaylorgraphics所有的代码都保留在'viewDidLoad'中。是否有'UITextFieldDelegate'方法打印字数? – sCha

相关问题