如何知道UITextView

时间:2015-09-21 14:52:49

标签: xcode swift text swift2 uisearchcontroller

我正在使用谷歌搜索UISearchController。我面对问题,UISearchBar.text中包含多少单词,我可以做出不同的行动。或者如何分隔不同的单词是分隔空间? 另外我想知道如何计算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")
        }
    }
}

1 个答案:

答案 0 :(得分:1)

对不起,我误解了你的问题......

//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)