我正在尝试放大用户位置作为屏幕的中心引用。我有以下代码:

MainViewController.h

#import <UIKit/UIKit.h>
#import "FlipsideViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

IBOutlet MKMapView *mapView;

@interface MainViewController : UIViewController <FlipsideViewControllerDelegate, MKMapViewDelegate> {
   MKMapView *mapView;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapView;

MainViewController.m
@implementation MainViewController
@synthesize mapView;

 - (void)viewDidLoad {
    [super viewDidLoad];
    mapView = [[MKMapView alloc]
           initWithFrame:self.view.bounds
           ];
    mapView.showsUserLocation = YES;
    mapView.mapType = MKMapTypeHybrid;
    mapView.delegate = self;
    [self.view addSubview:mapView];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    CLLocationCoordinate2D location;
    location.latitude = userLocation.coordinate.latitude;
    location.longitude = userLocation.coordinate.longitude;
    region.span = span;
    region.center = location;
    [mapView setRegion:region animated:YES];
 }

现在,我仅在最后一行[mapView setRegion:region animated:YES]上收到构建警告,指出:“'mapView'的本地声明隐藏了实例变量”

最佳答案

当执行mapView.showsUserLocation = YES;时,您要求它检索用户位置。这不会立即发生。随着时间的流逝, map View 通过委托(delegate)方法 mapView:didUpdateUserLocation 通知其委托(delegate)人用户位置可用。因此,您应该采用MKMapViewDelegate协议(protocol)并实现该方法。您应将所有放大代码移至此方法。

设置代表

- (void)viewDidLoad {
    [super viewDidLoad];
    mapView = [[MKMapView alloc]
           initWithFrame:CGRectMake(0,
                                    0,
                                    self.view.bounds.size.width,
                                    self.view.bounds.size.height)
           ];
    mapView.showsUserLocation = YES;
    mapView.mapType = MKMapTypeHybrid;
    mapView.delegate = self;
    [self.view addSubview:mapView];
}

更新了委托(delegate)方法
- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.005;
    span.longitudeDelta = 0.005;
    CLLocationCoordinate2D location;
    location.latitude = aUserLocation.coordinate.latitude;
    location.longitude = aUserLocation.coordinate.longitude;
    region.span = span;
    region.center = location;
    [aMapView setRegion:region animated:YES];
}

关于ios - Objective-C用户位置上的MKMapView中心,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6169919/

10-12 04:36