您在哪里以及如何居住_connections
?您使用该数组来决定每个部分的行数并填充这些行,但是_connections
正在返回整个列表。您需要将数据拆分为_connections
按字母顺序排列。
例如,也许您可以使用NSMutableArray
of NSMutableArray
s 按字母对数据进行分组。由于您似乎已经知道如何按字母顺序排序,现在您只需识别每个字符串的第一个字符即可将它们正确分组。为此,请尝试:
NSString *currentPrefix;
// Store sortedConnections as a class variable (as you've done with _connections)
// so you can access it to populate your table
sortedConnections = [[NSMutableArray alloc] init];
// Go through each connection (already ordered alphabetically)
for (BRConnection *connection in _connections) {
// Find the first letter of the current connection
NSString *firstLetter = [connection.fullName substringToIndex:1];
// If the last connection's prefix (stored in currentPrefix) is equal
// to the current first letter, just add the connection to the final
// array already in sortedConnections
if ([currentPrefix isEqualToString:firstLetter]) {
[[sortedConnected lastObject] addObject:connection];
}
// Else create a new array in sortedConnections to contain connections starting
// with this current connection's letter.
else {
NSMutableArray *newArray = [[NSMutableArray alloc] initWithObject:connection];
[sortedConnections addObject:newArray];
}
// To mark this latest array's prefix, set currentPrefix to contain firstLetter
currentPrefix = firstLetter;
}
(即使第一个字母未知,这种排序也可以工作。)
然后要获取每个部分的行数,请使用[sortedConnections objectAtIndex:section]
而不是 _connections:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [[sortedSearchResults objectAtIndex:section] count]; // hypothetically
} else {
return [[sortedConnections objectAtIndex:section] count];
}
}
要填充表,基本上使用相同的方法[sortedConnections objectAtIndex:indexPath.section]
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ConnectionCell"];
// Display connection in the table cell
BRConnection *connection = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
connection = [[sortedSearchResults objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]; // hypothetically
} else {
connection = [[sortedConnections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
}
cell.textLabel.text = connection.fullName;
cell.textLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:18];
cell.detailTextLabel.text = connection.company;
cell.detailTextLabel.font = [UIFont fontWithName:@"TitilliumText25L-400wt" size:12];
return cell;
}