xcode - UISearchController 不更新

标签 xcode swift ios8 uisearchcontroller

我在 ios8 和 swift 中使用 xcode 6.2 进行开发,我试图在 UITableViewController 中实现一个 UISearchController,它可以在搜索后更新,我写了一些简单的代码只是为了检查它是否有效,但是当我编译时,搜索栏在那里,但是当我输入文本并点击搜索时,没有任何反应:

这是我的代码:

import UIKit

class searchresult: UITableViewController,UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating {

    var result:[String] = ["a","b","c"]

    override func viewDidLoad() {
        super.viewDidLoad()

        var searchcon = UISearchController(searchResultsController: self)
        searchcon.delegate = self
        searchcon.searchBar.delegate = self
        searchcon.searchBar.sizeToFit()
        self.tableView.tableHeaderView = searchcon.searchBar
        searchcon.searchResultsUpdater = self
        searchcon.searchBar.showsSearchResultsButton = true
        self.definesPresentationContext = true
        searchcon.dimsBackgroundDuringPresentation = false

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
        cell.textLabel!.text = result[indexPath.row]
        return cell
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return result.count
    }


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }


    func updateSearchResultsForSearchController(searchController: UISearchController) {

        println("updating")
        result = ["1"]
        self.tableView.reloadData()   
    }
}

最佳答案

正如 Praveen Gowda IV 所说,您想将 searchResultsControllerself 更改为 nil。您还需要在 viewDidLoad 之外声明您的 searchcon:

var searchcon = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    // your implementation
}

但是,您获得的行为可能不是您想要的,因为 updateSearchResultsForSearchController 在搜索之前被调用:

Called when the search bar becomes the first responder or when the user makes changes inside the search bar. (Apple)

关于xcode - UISearchController 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29318113/

相关文章:

ios - 使用 CMTimeMapping 寻找 AVComposition 会导致 AVPlayerLayer 卡住

swift - Setter 方法不会分配属性

ios - 如何进行布局以处理 iOS 8 中自定义呈现的 View Controller 的通话中(双高)状态栏?

iphone - 如何在 Interface Builder 中输入 RGB 值?

ios - 当 VC 链接到 TabBarController 时,IBOutlet 和 IBAction 被禁用

ios - @选择器(方法:) conversion to Swift

ios - Swift 应用程序在设备上运行时崩溃 - dyld : Library not loaded: @rpath/libswiftCore. dylib

ios - SelfSizing Cell 仅适用于一个原型(prototype)电池

ios - RegisterUserNotificationSettings 在 ios 6.1 中不起作用

ios - 使用 `Visual Effect View with Blur` 减少模糊?