2017-05-18 81 views
0
不是搜索

我已經建立了一個UISearchController作爲標題爲我的tableview用下面的代碼:UISearchController中的UITableViewController

let mySearchController = UISearchController(searchResultsController: nil) 

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { 

    let keywords = searchBar.text 
    let finalKeywords = keywords?.replacingOccurrences(of: " ", with: "+") 

    searchUrl = "https://api.spotify.com/v1/search?q=\(finalKeywords!)&type=track&limit=20" 
    print(searchUrl) 

    callAlamo(url: searchUrl) 

} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.register(postCell.self, forCellReuseIdentifier: cellId) 
    tableView.separatorColor = .red 

    mySearchController.dimsBackgroundDuringPresentation = false 
    definesPresentationContext = true 
    mySearchController.delegate = self as? UISearchControllerDelegate 
    tableView.tableHeaderView = mySearchController.searchBar 

} 

我阿迪在searchBarButtonClicked功能,並在打印(searchUrl)斷點的內函數,但它從來沒有去過斷點。爲什麼searchBarSearchButtonClicked函數在我點擊搜索欄時沒有執行?

+0

你爲什麼鑄造'自我作爲UISearchControllerDelegate?這種低調可能返回'nil'。如果您在課堂中添加了實施的「UISearchControllerDelegate」,則不需要downcast。 – Paulw11

+0

我刪除了'mySearchController.delegate = self as? UISearchControllerDelegate'但它仍然不起作用 –

+0

你需要有一個委託,你需要將你的類設置爲委託,但我想知道爲什麼你有一個有條件的downcast來設置委託;它使我認爲你沒有正確設置委託實現,這就是爲什麼委託方法沒有被調用。 – Paulw11

回答

0

您正在設置錯誤的代表。一個UISearchBarController爲代表的財產,但您所用的方法是UISearchBarDelegate方法,所以你需要設置你的對象作爲委託包含了`UISearchBarController內的搜索欄:

mySearchController.searchBar.delegate = self 
+0

這工作,謝謝! –

+0

通常你會實現searchBar(textDidChange:),並在用戶輸入時執行搜索。使用計時器,以便僅在用戶停止鍵入半秒時執行搜索 – Paulw11

+0

如何在textDidChange函數內部實現計時器? –

相關問題