到目前为止,我已经通过填充数据库中的内容实现了 UITableView
通过 sqlite 数据库中的数组
storedContactsArray = [Sqlitefile selectAllContactsFromDB];
因此没有多个部分、部分标题并返回 storedContactsArray.count
作为行数。
现在我需要在 TableView 中填充相同的数据,但按字母顺序在字母顺序部分中设置的数据。
我试过
alphabetsArray =[[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [alphabetsArray count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return alphabetsArray;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [alphabetsArray objectAtIndex:section];
}
但是在 numberOfRowsInSectio
n 的情况下它会失败,因为 storedContactsArray
最初没有联系人
发生错误:-[__NSArrayM objectAtIndex:]: index 25 beyond bounds for empty array
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[storedContactsArray objectAtIndex:section] count]
}
任何使用完整链接的建议
最佳答案
要实现您的要求,您需要首先将所有数据按字母顺序分离到部分中。如下所示。
这里的部分是一个可变字典,我们将在其中获取所有按字母顺序排列的数据。
//Inside ViewDidLoad Method
sections = [[NSMutableDictionary alloc] init]; ///Global Object
BOOL found;
for (NSString *temp in arrayYourData)
{
NSString *c = [temp substringToIndex:1];
found = NO;
for (NSString *str in [sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
if (!found)
{
[sections setValue:[[NSMutableArray alloc] init] forKey:c];
}
}
for (NSString *temp in arrayYourData)
{
[[sections objectForKey:[temp substringToIndex:1]] addObject:temp];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[sections allKeys]count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] 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];
}
NSString *titleText = [[sections valueForKey:[[[sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = titleText;
return cell;
}
请尝试一下,我正在使用它并且工作正常 希望对你有帮助!!!
关于iphone - 如何在具有从数据库获取内容的 UITableView 中实现按字母顺序排列的节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13158634/