2014-05-16 80 views
-2

我有兩個數組和一個包含數字和國家的字典,如ViewDidLoad方法所示。 當用戶點擊特定單元格時,該國家將顯示在控制檯中。 我該怎麼做。 在此先感謝。如何通過選擇tableview單元格來獲取字典值?

- (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

請修復您的代碼格式化(縮進和擺脫所有多餘的空行)。 – rmaddy

回答

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]]); 
} 
+0

謝謝。我很感激 – user3615198

0
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    NSLog(@"%@", arrayOfCountries[indexPath.row]); 
} 
相關問題