【问题标题】:Implementing a search bar?实现搜索栏?
【发布时间】:2014-12-16 22:14:57
【问题描述】:

我有一个项目,在情节提要上创建了 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 现在只是在 swift 中,但没有解释该方法中的内容。

【问题讨论】:

    标签: cocoa-touch uisearchcontroller


    【解决方案1】:

    我想通了。伙计,其中一些事情非常简单,但您必须深入挖掘才能找到答案。你可能会认为 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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多