Я хотел бы добавить пользовательскую кнопку изображения в выноску аннотаций в определенных местах. Например, поиск в starbucks приведет к появлению маркера аннотаций для мест звездочек, а когда маркер будет нажат, выноска отобразит кнопку, которая затем направит вас к другому диспетчеру просмотра с информацией о Starbucks. В настоящий момент аннотация отображает адрес местоположения при нажатии, как я могу изменить это на отображение кнопки в выбранных местах по своему выбору? Я очень новичок в xcode и не могу найти много полезной информации об этом отношении к тому, как я разработал приложение до сих пор. Все работает по желанию, за исключением того, что я не знаю, с чего начать добавлять кнопку.добавить UIButton к выноску аннотации в mapkit
здесь мои ViewControllers
#import "ViewController.h"
@interface ViewController() <UISearchDisplayDelegate, UISearchBarDelegate>
@end
@implementation ViewController {
MKLocalSearch *localSearch;
MKLocalSearchResponse *results;
}
#pragma mark - View Lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
// Zoom the map to current location.
[self.ibMapView setShowsUserLocation:YES];
[self.ibMapView setUserInteractionEnabled:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeFollow];
}
#pragma mark - Search Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// Cancel any previous searches.
[localSearch cancel];
// Perform a new search.
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = searchBar.text;
request.region = self.ibMapView.region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error != nil) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Map Error",nil)
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show];
return;
}
if ([response.mapItems count] == 0) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show];
return;
}
results = response;
[self.searchDisplayController.searchResultsTableView reloadData];
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results.mapItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *IDENTIFIER = @"SearchResultsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IDENTIFIER];
}
MKMapItem *item = results.mapItems[indexPath.row];
cell.textLabel.text = item.name;
cell.detailTextLabel.text = item.placemark.addressDictionary[@"Street"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.searchDisplayController setActive:NO animated:YES];
MKMapItem *item = results.mapItems[indexPath.row];
[self.ibMapView addAnnotation:item.placemark];
[self.ibMapView selectAnnotation:item.placemark animated:NO];
[self.ibMapView setCenterCoordinate:item.placemark.location.coordinate animated:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeNone];
}
@end
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UISearchBar *ibSearchBar;
@property (strong, nonatomic) IBOutlet MKMapView *ibMapView;
@end
спасибо за ваш ответ, я просто немного разбираюсь в том, где должен быть размещен первый бит кода. Где будет находиться мой метод viewForAnnotation? Кажется, я не нашел его. – user3492592
Отредактировал мой ответ с помощью кода метода mapView: viewForAnnotation. Вы должны найти thit внутри 'ViewController.m' ... – Hari
Мне трудно получить этот код для правильной работы. Я помещаю оба метода в свой файл ViewController.m, но получаю сообщения об ошибках, в которых detalview является необъявленным идентификатором. Я совершенно не знаком с xcode. Я приношу свои извинения за недостаток знаний. – user3492592