如何知道 UITextView 中包含多少个单词

how to know how many words contains in UITextView

我正在 UISearchController 使用 google 搜索。我面临的问题是 UISearchBar.text 中包含多少个单词,我可以做出不同的操作。或者如何将不同的单词分开space? 我也想知道,如何计算 UITextView 中的单词数。

我的尝试

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    let text = searchController.searchBar.text!
    if text.containsString("www.") {
        let url = NSURL(string: "http://\(text)")!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    } else {
        if text.containsString(" ") == false {
        let url = NSURL(string: "https://www.google.com/#newwindow=1&q=\(text)")!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        } else {
            let url = NSURL(string: "https://www.google.com/#newwindow=1&q=\(text)")! // it is wrong
            let request = NSURLRequest(URL: url)
            webView.loadRequest(request)
            print("two words")
        }
    }
}

对不起,我看错了你的问题...

//Separate all words into an array
let allText = SearchText.text.componentsSeparatedByString(" ")

//then count the array
var wordsCount:Int = allText.count

要计算 UITextView.text 的字符数,您可以使用 count(UISearchBar.text)