【问题标题】:How to search for locations using UISearchBar with autocompletion and suggestions?如何使用带有自动完成和建议的 UISearchBar 搜索位置?
【发布时间】:2014-06-03 16:08:01
【问题描述】:
我正在开发一个应用程序,用户可以在其中搜索兴趣点,选择搜索结果,然后 MKMapView 将以结果坐标为中心。
我的问题是如何实现自动补全?我对MKLocalSearch 和MKLocalSearchRequest 进行了研究,这似乎是Apple 建议在iOS6.1+ 上进行位置搜索的API。但是,我找不到任何带有自动完成功能的示例或MKLocalSearch 和MKLocalSearchRequest 的建议。是否可以像 Apple 的地图应用程序一样自动完成位置搜索或显示建议列表?谢谢!
【问题讨论】:
标签:
ios
cocoa-touch
mkmapview
uisearchbar
mklocalsearch
【解决方案1】:
查看此帖子:https://stackoverflow.com/a/20141677/1464327
基本上,您可以提出多个请求。例如,当用户键入时,启动一个计时器,当计时器完成时,发出请求。每当用户键入时,取消前一个计时器。
实现文本字段委托的textField:shouldChangeCharactersInRange:replacementString:。
static NSTimer *_timer = nil;
[_timer invalidate];
_timer = [NSTimer timerWithTimeInterval:1.5 target:self selector:@selector(_search:) userInfo:nil repeats:NO];
然后实现_search方法发出请求。
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = self.textField.text;
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
// check for error and process the response
}];
我从来没有实现过这样的东西。我只是说我的出发点是什么。希望这会给你一些方向。