3

Я пытаюсь добавить UISearchController к программно созданному UITableView в классе UIViewController. Вот мой код:Не удается добавить UISearchController в UIViewController

var resultSearchController = UISearchController() 

var myTableView = UITableView() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    myTableView.frame = CGRectMake(0, 0, view.bounds.width, view.bounds.height) 
    myTableView.delegate = self 
    myTableView.dataSource = self 

    myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 

    self.resultSearchController = ({ 
     let controller = UISearchController(searchResultsController: nil) 
     controller.searchResultsUpdater = self //ERROR 
     controller.searchBar.delegate = self //ERROR 
     controller.dimsBackgroundDuringPresentation = false 
     controller.searchBar.sizeToFit() 

     self.myTableView.tableHeaderView = controller.searchBar 

     return controller 
    })() 

    UIApplication.sharedApplication().keyWindow?.addSubview(myTableView) 

} 

Две ошибки я получаю

- Cannot assign a value of type 'ViewController' to a value of type 'UISearchBarDelegate? 
- Cannot assign a value of type 'ViewController' to a value of type 'UISearchResultsUpdating? 

Этот код работает, когда мой класс подклассы с UITableViewController. Так почему же она не работает с UIViewController?

+0

Вам необходимо соответствовать 'UISearchBarDelegate'. –

+1

Вы добавили делегатов в контроллер вида? 'class ViewController: UIViewController, UISearchResultsUpdating, UISearchBarDelegate' – MendyK

+0

Спасибо! Это была моя проблема. – MortalMan

ответ

4

Убедитесь, что UIViewController в соответствии с протоколами UISearchBarDelegate и UISearchResultsUpdating.

class YourViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating { 
    // …truncated 
} 

UITableViewController автоматически делает это за кулисами.

Смежные вопросы