如果没有返回搜索结果,如何在 UITableView 中显示 "No results found"?

How to show "No results found" in UITableView, if there is no search result returned?

在 table 视图中,我显示 "No results found" 如果搜索控制器没有通过添加以下其他条件返回结果-

numberOfRowsInSection中:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        return 1
}

cellForRowAtIndexPath中:

else if self.searchController.active && self.searchController.searchBar.text?.characters.count > 0 &&
        self.filteredLanguages.count == 0 {
        cell.textLabel?.text = "No results found"
        cellImage = nil
        cell.userInteractionEnabled = false
        isNoResultCell = true
}

if filteredIndexPath!.row == userSettings.valueForKey("selectedRow") as? Int  && !isNoResultCell {
        cell.tintColor = UIColor.whiteColor()
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        lastSelectedRow = filteredIndexPath
}

我做了一些关于在 table 视图中显示 "No results found" 的方法的研究,但是在写完上面的逻辑之后。

根据一些帖子,当没有搜索结果时,我可以在 numberOfSectionsInTableView 的 table 的背景视图中添加一个 UILabel 作为子视图,如果搜索到则删除子视图结果返回。

我的问题是 - 哪个是最 resource/performance 精明的选择?

试试这个

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger numOfSections = 0;
    if (youHaveData)
    {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        numOfSections                 = 1;
       yourTableView.backgroundView   = nil;
    }
    else
    {   
        UILabel *noDataLabel         = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, yourTableView.bounds.size.width, yourTableView.bounds.size.height)];
        noDataLabel.text             = @"No data available";
        noDataLabel.textColor        = [UIColor blackColor];
        noDataLabel.textAlignment    = NSTextAlignmentCenter;
        yourTableView.backgroundView = noDataLabel;
        yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }

    return numOfSections;
}

您需要使用一个 UILabel,当您的 tableview 有记录时(即包含将在 tableview 中显示的记录的数组),它将被隐藏。

当您搜索一条记录但没有得到任何记录时,您可以隐藏表格视图并显示包含文本的标签 "No results found"。

我当然可以向您推荐这个很棒的库,https://github.com/dzenbot/DZNEmptyDataSet它将代表您工作。您可以轻松地设置占位符普通字符串或属性字符串或图像来代替 UICollectionViewUITableView.

当您获得数据时,只需重新加载您的对象,它就会隐藏该占位符。

使用:

viewDidLoad中:

self.tableView.emptyDataSetSource = self;
self.tableView.emptyDataSetDelegate = self;

执行以下委托:

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"No results found.";

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f], NSForegroundColorAttributeName: [UIColor darkGrayColor]};

    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

有关更多信息和用法,请查看上方link。

哦,是的,要在 Swift 项目中使用它:How to call Objective-C code from Swift

在 table 后面放置一个 UI 标签。当 table 计数为 0 时,使 table "isHidden" = true。这将隐藏 table,然后您将看到它下面的图层。 UI 标签将显示,因为它位于 table 视图的正下方。