实现搜索栏?

时间:2014-12-16 22:14:57

标签: cocoa-touch uisearchcontroller

我在故事板上创建了一个tableView的项目。这很简单,我按照教程来做,我的视图控制器看起来像这样

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    cell.textLabel.text = restaurantDisplayNames[indexPath.row];

    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES
     ];
}

因此,当您点击一个单元格时,它会在旁边放置一个复选标记。现在我希望人们能够搜索到的东西。问题是,Apple更改了iOS 8的搜索栏,并且据说更简单,但我找不到UISearchController上替换了已删除方法的任何教程。

所以我搜索栏和搜索显示控制器拖放到我的视图控制器中并添加了UISearchControllerDelegate, UISearchResultsUpdating>协议声明,但是我遇到了崩溃:

'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

每当我点按搜索栏时。

我也有方法

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{

}

但它是空的,因为我不知道该放什么。据说它非常简单,只需要几行代码就可以启动并运行,但是我在这里找到的一个教程:http://www.stuartbreckenridge.com/blog/examining-the-new-uisearchcontroller-api现在只是快速但不解释该方法的内容。 / p>

1 个答案:

答案 0 :(得分:0)

我明白了。男人,其中一些事情太简单了,你必须深入挖掘才能找到答案。您认为Apple可以在XCode中提供一些关于这些事情的提示,一些警告或其他内容,但这是我如何修复它:

显然你需要添加

if (!cell){
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}

cellForRowAtIndexPath:方法中,它看起来像这样:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = restaurantDisplayNames[indexPath.row];

    return cell;
}

因此,如果它不存在,它会生成单元格。不知道为什么,但是很好......