嘗試使用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? – Adarkas2302
此錯誤正在打印在控制檯中: 「結果」=>:0 –
ctaylorgraphics
但是,這是正確的..它應該是0在該位置。我試過你的代碼並添加了我的答案。然後它打印2. –