【问题标题】:Search Bar displaying results in both sections of Table View搜索栏在表格视图的两个部分中显示结果
【发布时间】:2017-02-28 10:03:09
【问题描述】:

我的 iOS 应用程序出现问题,我在表格视图中添加了 2 个部分,但是搜索栏在我的两个部分中都显示了结果,而不是全部显示。

只是在这里猜测,但问题可能是因为搜索栏没有自己的部分,所以它将结果放在两者中?我必须添加另一个部分吗?修复代码?或者添加另一个tableview/视图控制器来处理filteredArray?

代码:

dataArray 是我从服务器获取所有阵列的地方

followedArray 是某些数组从 dataArray 中去的地方

filteredArray是从dataArray中搜索到的数组

numberOfRowsInSection

if (!isFiltered) {

    if (section == 0) {
        return [followedArray count];
    }
    else {
        return [dataArray count];
    }
}
return [filteredArray count];

titleForHeaderInSection

if (section == 0) {
    return @"Followed Data";
}
else {
    return @"All Data";
}

cellForRowAtIndexPath

Data * dataObject;
if (!isFiltered) {

    if (indexPath.section == 0) {
        dataObject = [followedArray objectAtIndex:indexPath.row];
    }
    else {
        dataObject = [dataArray objectAtIndex:indexPath.row];
    }
}
else {
    dataObject = [filteredArray objectAtIndex:indexPath.row];
}

searchBar textDidChange

if (searchText.length == 0) {
    isFiltered = NO;
} else {
    isFiltered = YES;

    filteredArray = [[NSArray alloc] init];
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"self.dataName contains[c] %@", searchText];
    filteredArray = [dataArray filteredArrayUsingPredicate:resultPredicate];

}
[myTableView reloadData];

--------------------------------

我在这里做错了什么?还是我错过了什么?

我希望在第 1 节中使用 followArray,在第 2 节中使用 dataArray,并在使用搜索栏搜索 dataArray 以独立显示它时,而不是像现在这样在两个部分中显示它。谢谢!

【问题讨论】:

    标签: arrays xcode uitableview uisearchbar sections


    【解决方案1】:

    非常简单的答案,但我是 iOS 新手

    // Title for Header
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    
        if !(searchController.isActive && searchController.searchBar.text != "") {
    
            if section == 0 {
                return "Followed Data"
            }
            else {
                return "All Data"
            }
        }
    
        return "Filtered Data"
    }
    
    // Number of Rows in Section
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        if !(searchController.isActive && searchController.searchBar.text != "") {
    
            if section == 0 {
    
                return followedArray.count
            }
            else if (section == 1) {
    
                return dataArray.count
            }
        }
    
        return filteredArray.count
    }
    
    // Number of Sections
    func numberOfSections(in tableView: UITableView) -> Int {
    
        if !(searchController.isActive && searchController.searchBar.text != "") {
    
            return 2
        }
    
        return 1
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多