我有两个数组和一个字典,其中包含ViewDidLoad方法中显示的数字和国家/地区。 当用户单击特定单元格时,该国家/地区将显示在控制台中。 我怎样才能做到这一点。 提前谢谢。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayofNumbers = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
arrayofCountries = [[NSArray alloc]initWithObjects:@"India", @"America",@"Pakistan",@"Germany",@"Australia",nil];
dictOfCountries = [[NSDictionary alloc] initWithObjects:arrayofNumbers forKeys:arrayofCountries];
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:selectedIndexPath];
NSLog(@"%@", cell.textLabel.text);
}
答案 0 :(得分:0)
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"%@", arrayOfCountries[indexPath.row]);
}
答案 1 :(得分:0)
为什么要创建NSDictionary
和额外NSArray
来保存indexPath?您可以通过arrayofCountries
数组中的索引访问所选国家/地区。
将viewDidLoad
方法更改为:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayofCountries = [[NSArray alloc]initWithObjects:@"India",@"America",@"Pakistan",@"Germany",@"Australia",nil];
}
并实施didSelectRowAtIndexPath
委托方法如下
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// when user select a cell in your tableView the indexPath of this cell is the
// index of your dataSource array in your case this is arrayOfCountries
NSLog(@"Selected Country ----> %@", [arrayOfCountries objectAtIndex:[indexPath.row]]);
}