2016-05-03 55 views
4

你好我正在GMSAutocompleteViewController在我的應用程序工作。我有一個uitextfield在我的視圖控制器時,我tapp textfield搜索使用谷歌API的地方,一個新的視圖是開放的,由谷歌供電。請看我的代碼。如何在uitextfield上應用自定義搜索,以便使用gmsAutocomplete視圖控制器進行搜索。

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 



tappedTextField = textField; 
     GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init]; 
     acController.delegate = self; 
     [self presentViewController:acController animated:YES completion:nil]; 



    } 


    - (void)viewController:(GMSAutocompleteViewController *)viewController 
    didAutocompleteWithPlace:(GMSPlace *)place { 
// Do something with the selected place. 
NSLog(@"Place name %@", place.name); 
NSLog(@"Place address %@", place.formattedAddress); 
NSLog(@"Place attributions %@", place.attributions.string); 
NSLog(@"lat and log%f", place.coordinate.latitude); 
NSLog(@"lang %f", place.coordinate.longitude); 



    tappedTextField.text = place.name; 



[self dismissViewControllerAnimated:YES completion:nil]; 
} 

    - (void)viewController:(GMSAutocompleteViewController *)viewController 
    didFailAutocompleteWithError:(NSError *)error { 
// TODO: handle the error. 
     NSLog(@"error: %ld", (long)[error code]); 
    [self dismissViewControllerAnimated:YES completion:nil]; 
    } 

    // User canceled the operation. 
- (void)wasCancelled:(GMSAutocompleteViewController *)viewController { 
NSLog(@"Autocomplete was cancelled."); 
[self dismissViewControllerAnimated:YES completion:nil]; 
    } 

我不想要移動到另一種觀點認爲在文本框TAPP進行搜索。有可能我只能從文本字段中搜索地點嗎?

Scrren of my view controller

當我在目的地文本框單擊一個新的觀點出現了搜索,但我只需要請TAPP文本字段後,屏幕從文本框進行搜索。

This screen after click of textfield

+0

有沒有可能做這個任務,或者我總是使用視圖由谷歌只提供動力? –

+0

嗨它解決了嗎? –

回答

3

這聽起來像你追求的是在一個表中立即顯示自動完成結果的文本框下方當文本字段處於活動狀態(即類似於this的東西)。

您可以通過創建一個UITableView來顯示在UI中正確的位置。而不是使用GMSAutocompleteViewController,創建一個GMSAutocompleteTableDataSource並將其設置爲UITableView的委託和數據源。例如:

_tableDataSource = [[GMSAutocompleteTableDataSource alloc] init]; 
_tableDataSource.delegate = self; 
tableView.delegate = _tableDataSource; 
tableView.dataSource = _tableDataSource; 

當文本字段文本更改時,請在表數據源上調用sourceTextHasChanged

[_tableDataSource sourceTextHasChanged:textField.text]; 

最後,有父視圖控制器實現GMSAutocompleteTableDataSourceDelegate協議

有中所含的GoogleMaps CocoaPod樣本應用程序,是接近你想要的一些示例代碼。在下載的Pods目錄中查找SDKDemoAutocompleteWithTextFieldController.m

+0

你能幫我在同一場景嗎? @AndrewR –

1

我用這個代碼來實現你所要求的相同行爲。

-(void)LoadJson_search{ 
searchArray=[[NSMutableArray alloc]init]; 
NSLog(@"str......%@",strSearch); 

NSString *str1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&key=AIzaSyD2NttUhPQ4PKvpju97qpeWj8SYnZtzt0s",strSearch]; 
NSLog(@"%@",strSearch); 
NSURL *url = [NSURL URLWithString:str1]; 

NSData *data = [NSData dataWithContentsOfURL:url]; 
NSError *error=nil; 
if(data.length==0) 
{ 

} 
else 
{ 
    NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

    // NSLog(@"1,,,,%@",jsondic); 
    [searchArray removeAllObjects]; 
    if([[jsondic objectForKey:@"status"]isEqualToString:@"ZERO_RESULTS"]) 
    { 

    } 
    else if([[jsondic objectForKey:@"status"]isEqualToString:@"INVALID_REQUEST"]) 
    { 
    } 
    else 
    { 
     for(int i=0;i<[jsondic.allKeys count];i++) 
     { 
      //['predictions'][0]['description'] 
      NSString *str1=[[[jsondic objectForKey:@"predictions"] objectAtIndex:i] objectForKey:@"description"]; 
      [searchArray addObject:str1]; 
     } 
     tbl_vw1.hidden=FALSE; 
    } 
    if (searchArray.count == 0) { 
     tbl_vw1.hidden = TRUE; 
    }else{ 
     [tbl_vw1 reloadData]; 
    } 
} 

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{ 
if (textField.tag == 3) { 
    strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    if([string isEqualToString:@" "]){ 

    }else{ 
     [self LoadJson_search]; 
    } 
} 
return YES; 

}

而上實現代碼如下didSelect方法使用以下

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
strSelectedAddress = [searchArray objectAtIndex:indexPath.row]; 
[self.eventDict setObject:strSelectedAddress forKey:@"venue"]; 
// [self geoCodeUsingAddress:str_select_address]; 

tbl_vw1.hidden=TRUE; 
[tbl_vw reloadData]; 
} 

重裝表後,用這的cellForRowAtIndexPath更新選定的地名。

cell.txt.text = [self.eventDict objectForKey:@"venue"]; 

希望這可以幫助你。 :)

+0

兄弟,我有一個textfield,在它下面是一個tableview,當用戶點擊文本框它顯示相關的地方,兄弟我沒有得到如何做到這一點,你可以幫助我嗎?我第一次嘗試,面臨很多問題。 @Nij –

+0

你能幫我嗎? @Nij –

+0

檢查文本字段的委託方法並顯示你的tableview。 – Nij

0

這是我基於@ Nij的答案。這會讓你完全滿意......

#import "ViewController.h" 
#import <GooglePlaces/GooglePlaces.h> 

@interface ViewController() <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource> { 

    NSMutableArray *searchArray; 
    NSString *strSearch; 

} 

@property (weak, nonatomic) IBOutlet UITextField *searchTextfeild; 
@property (weak, nonatomic) IBOutlet UITableView *tbl_vw1; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    _searchTextfeild.delegate = self; 
    _tbl_vw1.delegate = self; 
    _tbl_vw1.dataSource = self; 
    _tbl_vw1.hidden = YES; 

    _searchTextfeild.clearButtonMode = UITextFieldViewModeAlways; 

} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (void)LoadJson_search{ 

    searchArray=[[NSMutableArray alloc]init]; 
    // NSLog(@"str......%@",strSearch); 
    // This API key is from https://developers.google.com/maps/web/ 
    NSString *str1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%@&key=AIzaSyAm7buitimhMgE1dKV2j4_7doULluiiDzU", strSearch]; 
    NSURL *url = [NSURL URLWithString:str1]; 

    NSData *data = [NSData dataWithContentsOfURL:url]; 
    NSError *error=nil; 
    if(data.length==0) 
    { 

    } 
    else 
    { 
     NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

    //   NSLog(@"1,,,,%@",jsondic); 
     [searchArray removeAllObjects]; 
     if([[jsondic objectForKey:@"status"]isEqualToString:@"ZERO_RESULTS"]) 
     { 

     } 
     else if([[jsondic objectForKey:@"status"]isEqualToString:@"INVALID_REQUEST"]) 
     { 
     } 
     else 
     { 
      for(int i=0;i<[jsondic.allKeys count];i++) 
      { 
       NSString *str1=[[[jsondic objectForKey:@"predictions"] objectAtIndex:i] objectForKey:@"description"]; 
       [searchArray addObject:str1]; 
      } 
      _tbl_vw1.hidden = NO; 
    //   NSLog(@"%@", searchArray); 
     } 
     if (searchArray.count == 0) { 
      _tbl_vw1.hidden = YES; 
     }else{ 
      [_tbl_vw1 reloadData]; 
     } 
    } 
} 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{ 
    if (textField.tag == 3) { 
     strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
     if([string isEqualToString:@" "]){ 

     }else{ 
      [self LoadJson_search]; 
     } 
    } 
    return YES; 
} 


- (BOOL)textFieldShouldClear:(UITextField *)textField{ 
    _tbl_vw1.hidden = YES; 
    [_tbl_vw1 reloadData]; 

    return YES; 
} 


//TableView delegates 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return searchArray.count; 
} 


-(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 

    UITableViewCell *cell = [_tbl_vw1 dequeueReusableCellWithIdentifier:@"cell"]; 
    if(!cell) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; 
    } 
// NSLog(@"searchArray ==== %@", searchArray); 
    cell.textLabel.text = [searchArray objectAtIndex:indexPath.row]; 

    return cell; 
} 


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

    _searchTextfeild.text = [searchArray objectAtIndex:indexPath.row]; 

    _tbl_vw1.hidden = YES; 
    [_tbl_vw1 reloadData]; 

} 
+0

使用主隊列重新載入表視圖數據,dispatch_async(dispatch_get_main_queue(),^ { [_tbl_vw1 reloadData]; }); – iOS

+0

這個代碼只會顯示兩個地方,如果你想顯示兩個以上的地方......改變json的dic計數就像這樣... for(int i = 0; i <[[jsondic objectForKey:@「predictions 「] count]; i ++) NSString * str1 = [[[jsondic objectForKey:@」predictions「] objectAtIndex:i] objectForKey:@」description「]; [searchArray addObject:str1]; } – iOS

相關問題