ios - 如何将 TableView 中的数组组织成按字母顺序排列的部分

标签 ios objective-c

我正在制作一个带有表格 View 的应用程序,我希望能够像 native 联系人应用程序一样对表格数据进行排序,其中名称的首字母与具有相同首字母的所有其他名称一起排序.我正在使用可变数组。

这是实现文件中表的代码(这不是文件中的所有代码,只是其中用于表的部分):

    - (void)viewDidLoad
{
    [super viewDidLoad];


    self.doctorNames = [NSMutableArray.alloc
                        initWithObjects:@"Aaron Smith", @"Michael Jordan", @"Cormac Chester", @"Marcus Baloutine", @"Joe Schmo", @"Sly James", @"Barack Obama", @"Joe Biden", @"Superman", @"Batman", @"Robin", @"Commissioner Gorden", @"Joseph Gordon Levitt" ,nil];
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    if(tableView == self.searchDisplayController.searchResultsTableView)
    {
        return [searchResults count];
    }
    else
    {
        return [self.doctorNames count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [UITableViewCell.alloc
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
    }
    else
    {
        cell.textLabel.text = [doctorNames objectAtIndex:indexPath.row];
    }


    return cell;
}

-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate*resultPredicate =[NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    searchResults =[doctorNames filteredArrayUsingPredicate:resultPredicate];
}


-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString*)searchString
{
    [self filterContentForSearchText:searchString
    scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
    objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    return YES;
}

最佳答案

您的数据结构设置不正确。您需要一组截面数据。数组的每个元素都应该是一个字典。每个字典都应该有一个用于部分标题的键和一个用于该部分中行数组的键。

拥有一个大数组不适合分区表。

关于ios - 如何将 TableView 中的数组组织成按字母顺序排列的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641410/

相关文章:

ios - 为什么导航栏背景颜色没有改变?

iphone - 使用字符串中的对象运行方法

objective-c - Xcode 在 NSAttributedString 上调用 RTFFromRange 时生成警告,documentAttributes 为 nil

iphone - NSNumber/NSString 数学返回正确的值但带有负号

objective-c - 将项目添加到 sqlite3 数据库不起作用

objective-c - 为什么我的时区没有保存到我的 NSDate 中?

objective-c - 构建具有多个可拉伸(stretch)图像的 UIImage

ios - 具有垂直滚动功能的 View 内部的 UICollectionView 和 ScrollView

ios - 如何在 Swift 中将代理对转换为 Unicode 标量

ios - 快速处理文本字段中的测试更改事件