带有UITableView的UISearchBar包含自定义单元格=>空白单元格

Erz*_*iel 0 iphone objective-c uitableview uisearchbar ios

  • 我有一个包含自定义单元格的UITableView.一切正常.但之后,我决定添加一个searchBar以便...搜索!

  • 所以,我添加了一个"搜索栏和搜索显示控制器""对象库"在我的XIB文件,在UITableView的下.

  • 我为自定义单元格创建了一个特定的类:

    "CustomCell.h"

    @class CustomCell;
    
    @interface CustomCell : UITableViewCell
    {
    }
    
    @property (weak, nonatomic) IBOutlet UILabel *lblDate;
    @property (weak, nonatomic) IBOutlet UILabel *lblAuteur;
    
    @end
    
    Run Code Online (Sandbox Code Playgroud)

    "CustomCell.m"

    no interesting stuff
    
    Run Code Online (Sandbox Code Playgroud)

    "CustomCell.xib"

    在此输入图像描述

  • "事件"类:

    @interface Event : NSObject
    {
    }
    
    @property (strong, nonatomic) NSString *desc;
    @property (strong, nonatomic) NSString *dateCreation;
    
    @end
    
    Run Code Online (Sandbox Code Playgroud)
  • 包含UITableViewUISearchBar的视图:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"cell";
    
        // Determinate the current event
        Event *currentEvent;
        if (tableView == self.searchDisplayController.searchResultsTableView)
            currentEvent = [filteredArray objectAtIndex:indexPath.row];
        else
            currentEvent = [notFilteredArray objectAtIndex:indexPath.row];
    
        CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if(cell == nil)
            cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    
        cell.lblAuteur.text = [currentEvenement desc];
        cell.lblDate.text = [currentEvenement dateCreation];
    
        return cell;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 好的,现在我们可以解决我的问题.加载tableView后,自定义单元格显示良好.但是如果我使用SearchBar则不是:

    1. 如果存在desc属性等于"foo"的事件,并且如果我在SearchBar中输入"bar",则会获得"No results"消息.这是正常的.
    2. 如果存在desc属性等于"foo"的事件,并且如果我在SearchBar中输入"foo",则单元格正在显示,但没有其内容!我只是看到了细胞的边界,以及lblDatelblAuteur等于为零.

为什么我这样做?非常感谢您的帮助......我确切地说,filteredArraynotFilteredArray已正确填充(我多次检查过).这意味着搜索机制运行良好.

小智 7

经过多次"搜索"(双关语),我发现了问题.

当您使用原型单元格引用tableview时,您不能依赖于传入的tableview,因为有时该tableview是没有原型单元格的搜索表视图.

而不是......

HomeTabCell *cell = (HomeTabCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Run Code Online (Sandbox Code Playgroud)

使用原型单元直接连接到表视图,替换上面的"tableview"

HomeTabCell *cell = (HomeTabCell *)[self.HomeTableView dequeueReusableCellWithIdentifier:CellIdentifier];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!