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"];
上面是我的字典。我想要一个tableview,其中UITableViewCell中的文本将显示“Site1”,并且子文本将具有URL。
我知道这会给我所有的钥匙
NSArray *keys = [dictionaryOfWebsites allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(@"%@ is %@",key, [dict objectForKey:key]);
}
你的帮助将不胜感激
如果我的方法不是最好的方法,请告诉我,以便我可以从您的建议中学习。
答案 0 :(得分:3)
尝试
- (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;
}
编辑:最好有一组字典用于这种表示。
每个字典都有两个键值对Title和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;
}
答案 1 :(得分:0)
你可以尝试:
- (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;
}
在这种情况下,将keys数组声明为属性。