2015-08-28 80 views
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

您是否将代表添加到视图控制器? '类ViewController:UIViewController,UISearchResultsUpdating,UISearchBarDelegate' – MendyK

+0

谢谢!这是我的问题。 – MortalMan

回答

4

请确保您的UIViewController符合协议UISearchBarDelegateUISearchResultsUpdating

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

UITableViewController自动在幕后进行此操作。