[英]How do I load the data from my NSMutableDictionary to my UITableView
dictionaryOfWebsites = [[NSMutableDictionary alloc] init];
[dictionaryOfWebsites setObject:@"http://www.site1.com" forKey:@"Site1"];
[dictionaryOfWebsites setObject:@"http://www.site2.com" forKey:@"Site2"];
[dictionaryOfWebsites setObject:@"http://www.site3.com" forKey:@"Site3"];
[dictionaryOfWebsites setObject:@"http://www.site4.com" forKey:@"Site4"];
Above is my dictionary. 以上是我的字典。 I want to have a tableview where the text in the UITableViewCell will say "Site1" and the subtext will have the URL. 我想拥有一个Tableview,其中UITableViewCell中的文本将显示“ Site1”,而子文本将具有URL。
I know this will get me all the keys 我知道这会给我所有的钥匙
NSArray *keys = [dictionaryOfWebsites allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(@"%@ is %@",key, [dict objectForKey:key]);
}
you're help would be greatly appreciated 您的帮助将不胜感激
If my approach is not the best one, please let me know so I can learn from your recommendations. 如果我的方法不是最好的方法,请告诉我,以便我从您的建议中学习。
Try 尝试
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[dictionaryOfWebsites allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Initialize cell of style subtitle
NSArray *keys = [[dictionaryOfWebsites allKeys]sortedArrayUsingSelector:@selector(compare:)];
NSString *key = keys[indexPath.row];
cell.textLabel.text = key;
cell.detailTextLabel.text = dictionaryOfWebsites[key];
return cell;
}
Edit : It is better to have an array of dictionaries for these kind of representation. 编辑:最好有一系列用于此类表示的字典。
Each dictionary with two key value pairs Title and Subtitle. 每个词典都有两个键值对,分别是“标题”和“字幕”。
self.dataArray = [NSMutableArray array];
NSDictionary *dict = @{@"Title":@"Site1",@"Subtitle":@"http://www.site1.com"};
[dataArray addObject:dict];
//Add rest of the dictionaries to the dataArray
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Initialize cell of style subtitle
NSDictionary *dict = self.dataArray[indexPath.row];
cell.textLabel.text = dict[@"Title"];
cell.detailTextLabel.text = dict[@"Subtitle"];
return cell;
}
You could try: 您可以尝试:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell initialization code
NSString *title = [keys objectAtIndex:indexPath.row];
cell.textLabel.text = title;
cell.detailTextLabel.text = [dictionaryOfWebsites objectForKey:title];
return cell;
}
in that case declare keys array as a property. 在这种情况下,将keys数组声明为属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.