问题
I have an array of names I want to make section headers as alphabets such as A B C. Also the indexes. What's the most efficient way of making Sections out of an array of names
回答1:
Here are i developed method that process on NSArray
and created NSDictionary
that you aspected.
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray* internalArray = [NSMutableArray arrayWithObjects:@"abc",@"xyz",@"aa",@"bb", nil];
NSDictionary* dictStructued = [self sortArrayAndMakeStructur:internalArray];
NSLog(@"Output : %@",dictStructued.description);
}
Here is your whole method..
-(NSMutableDictionary*)sortArrayAndMakeStructur:(NSArray*)array{
NSMutableDictionary* dictIndexes = [[NSMutableDictionary alloc]init];
NSArray* sortedArray = [array sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
for (int i=0; i<[sortedArray count]; i++) {
NSString* strName = sortedArray[i];
if ([[dictIndexes allKeys] containsObject:[[strName substringToIndex:1] uppercaseString]]) {
NSMutableArray* internalArray = [NSMutableArray arrayWithArray:[dictIndexes valueForKey:[[strName substringToIndex:1] uppercaseString]]];
[internalArray addObject:strName];
[dictIndexes setObject:internalArray forKey:[[strName substringToIndex:1] uppercaseString]];
}
else{
NSMutableArray* internalArray = [NSMutableArray arrayWithObjects:strName, nil];
[dictIndexes setObject:internalArray forKey:[[strName substringToIndex:1] uppercaseString]];
}
}
return dictIndexes;
}
Here section count = [[dictStructued allKeys] count];
Number Of Row = [[dictIndexes valueForKey:yourKey] count];
Output :
{
A = (
aa,
abc
);
B = (
bb
);
X = (
xyz
);
}
回答2:
Please use nesting NSArray or NSDictionary that has array with each key.
Cited from: http://www.appcoda.com/ios-programming-index-list-uitableview/
回答3:
First, we sort them with alphabet:
NSMuatableArray* sortedArray = [anArray sortedArrayUsingSelector:
@selector(localizedCaseInsensitiveCompare:)];
and we populate it normally in - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
Hope this could help.
来源:https://stackoverflow.com/questions/31201038/how-to-make-uitableview-indexes-and-sections-from-array-of-stings