Reputation: 748
So I have a little problem here, I think I made my point clear in the title of this post. I want to sort UITableView
headers according to the order I declared them in code. I tried surfing the net already but I can't find any solution.
I think one from here can help. Thanks in advance!
EDIT: This is my code to of the table view contents
NSDictionary *temp = [[NSDictionary alloc]initWithObjectsAndKeys:accSettingsOpts, @"Account",notifSettingsOpts,@"Notifications",aboutOpts,@"About",logoutOpt,@"Sign Out",nil];
I want to display the table view sorted by
-Account
-Notifications
-About
-Sign Out
But it displays as
-About
-Account
-Notifications
-Sign Out
EDIT: This is how the problem is addressed.
Based from the answer provided in which I accepted below, I modified it as
@interface myClass ()
NSArray *headerArr;
@end
at viewDidload
I added
headerArr = [[NSArray alloc]initWithObjects:@"Account",@"Notifications",@"About",@"Sign Out", nil];
and lastly...
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return [headerArr objectAtIndex:section];
}
Thanks for the help guys. I didn't imagine that it's just that simple.
Upvotes: 1
Views: 109
Reputation: 726599
The reason the order is different from the declaration order is that NSDictionary
is unordered: it is sorted based on the hash code of your strings, which is rather arbitrary.
To force a particular order, use a container with a fixed order, such as NSArray
. For example, you can store your accSettingsOpts
, notifSettingsOpts
, and so on, in a single array, add a header
property to the Opts
class, and pull that property to set section headers in your UITableView
.
Upvotes: 2
Reputation: 131416
A dictionary is an unordered collection. If you store your items in a dictionary, the order in which you defined them is not saved anywhere.
Table views are an inherently ordered list of objects. Therefore a dictionary is not suitable as a way of storing the items for a table view. An array, however, makes a natural data source for a table view.
Use an array rather than a dictionary. It's as simple as that. You can use an array of dictionaries, or an array of some other data objects, and then write your cellForRowAtIndexPath method to extract the data from your model (array elements) and install the values in the cell.
Upvotes: 2