【问题标题】:Current location button on ios MKMapViewios MKMapView 上的当前位置按钮
【发布时间】:2015-01-11 18:50:16
【问题描述】:

我在我的 iOS 应用程序中使用 MKMapView。我的视图中有搜索栏。如果我在地图上搜索位置,我会在该搜索位置上添加注释。现在的问题是,我想回到我现在的位置。我见过谷歌地图应用程序,他们在地图上有一个按钮,可以将用户发送到当前位置。

如何显示该按钮?以及如何获得该按钮的点击事件?

【问题讨论】:

标签: ios iphone mkmapview mapkit


【解决方案1】:

解决方案 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];
}

【讨论】:

  • 这会将地图发送到用户位置,但是如何添加按钮?
  • @selector(zoomToUserLocation) remove ":" 因为你不需要将按钮作为参数发送到方法
【解决方案2】:
- (void)viewDidLoad
{
    [super viewDidLoad];    
    MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
    self.navigationItem.rightBarButtonItem = buttonItem;
}

【讨论】:

    【解决方案3】:

    您需要创建一个MKUserTrackingBarButtonItem 并在构造函数中将MKMapview 传递给它,然后将该按钮项添加到导航菜单(或者您的按钮应该在哪里)。

    (void) viewDidLoad
    {
        [super viewDidLoad];    
        MKUserTrackingBarButtonItem *buttonItem = [[MKUserTrackingBarButtonItem alloc] initWithMapView:self.map];
        self.navigationItem.rightBarButtonItem = buttonItem;
    }
    

    【讨论】:

      【解决方案4】:

      斯威夫特 3+

      let buttonItem = MKUserTrackingBarButtonItem(mapView: mapView)
      self.navigationItem.rightBarButtonItem = buttonItem
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        • 2012-09-16
        • 1970-01-01
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多