showsUserLocation操作附加到按钮不起作用

时间:2015-01-16 03:36:19

标签: ios8 mapkit location-services

我在应用中遇到地图视图问题。我创建了一个按钮,单击该按钮时应该在地图上显示用户位置,但没有任何反应(不会出现错误消息)。

我认为问题可能在于我写代表的方式。相关的.h和.m文件中的代码如下:

mapViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface mapViewController : UIViewController  {
MKMapView *mapview;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapview;
-(IBAction)setMap:(id)sender;
-(IBAction)getCurrentLocation:(id)sender;
@property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
@end

mapViewController.m

#import "mapViewController.h"
@interface mapViewController ()
@end
@implementation mapViewController {
CLLocationManager *locationManager;
}
@synthesize mapview;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.requestWhenInUseAuthorization;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)setMap:(id)sender {
switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
case 0:
    mapview.mapType = MKMapTypeStandard;
    break;
case 1:
    mapview.mapType = MKMapTypeSatellite;
    break;
case 2:
    mapview.mapType = MKMapTypeHybrid;
    break;
   default:
    break;
}
}
-(IBAction)getCurrentLocation:(id)sender {
mapview.showsUserLocation = YES;
}
@end

非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:0)

您必须实现MapKit委托。 (确保在视图控制器的.h中添加代理签名)

- (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];
 }

额外:要处理App是否在前台:

我们添加了2个事件观察者来观察App正在进入后台/返回活动状态:

- (void)viewDidLoad{
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appToBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appReturnsActive) name:UIApplicationDidBecomeActiveNotification object:nil];
} 

- (void)appToBackground{
  [mapview setShowsUserLocation:NO];
}

- (void)appReturnsActive{
  [mapview setShowsUserLocation:YES];
}