【发布时间】:2015-01-11 18:50:16
【问题描述】:
我在我的 iOS 应用程序中使用 MKMapView。我的视图中有搜索栏。如果我在地图上搜索位置,我会在该搜索位置上添加注释。现在的问题是,我想回到我现在的位置。我见过谷歌地图应用程序,他们在地图上有一个按钮,可以将用户发送到当前位置。
如何显示该按钮?以及如何获得该按钮的点击事件?
【问题讨论】:
标签: ios iphone mkmapview mapkit
我在我的 iOS 应用程序中使用 MKMapView。我的视图中有搜索栏。如果我在地图上搜索位置,我会在该搜索位置上添加注释。现在的问题是,我想回到我现在的位置。我见过谷歌地图应用程序,他们在地图上有一个按钮,可以将用户发送到当前位置。
如何显示该按钮?以及如何获得该按钮的点击事件?
【问题讨论】:
标签: ios iphone mkmapview mapkit
解决方案 1:
将 UIButton 拖到情节提要中的 UIViewController 并将其连接到 ViewController.m 中的 IBAction。
-(IBAction)zoomToUserLocation:(id)sender{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;
[mapView setRegion:mapRegion animated: YES];
}
解决方案 2:
或者您可以像这样以编程方式创建按钮:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
action:@selector(zoomToUserLocation)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"My Location" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];
使用以下方法:
-(void)zoomToUserLocation{
MKCoordinateRegion mapRegion;
mapRegion.center = mapView.userLocation.coordinate;
mapRegion.span.latitudeDelta = 0.2;
mapRegion.span.longitudeDelta = 0.2;
[mapView setRegion:mapRegion animated: YES];
}
【讨论】:
- (void)viewDidLoad
{
[super viewDidLoad];
MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
self.navigationItem.rightBarButtonItem = buttonItem;
}
【讨论】:
您需要创建一个MKUserTrackingBarButtonItem 并在构造函数中将MKMapview 传递给它,然后将该按钮项添加到导航菜单(或者您的按钮应该在哪里)。
(void) viewDidLoad
{
[super viewDidLoad];
MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
self.navigationItem.rightBarButtonItem = buttonItem;
}
【讨论】:
斯威夫特 3+
let buttonItem = MKUserTrackingBarButtonItem(mapView: mapView)
self.navigationItem.rightBarButtonItem = buttonItem
【讨论】: