2015-06-23 103 views
0

我正在尝试使用Xcode 6.3和Swift做iOS应用程序。我使用MKMapView来跟踪用户的位置。问题是,如果我滚动地图,我立即返回到用户位置。这是我的代码:无法滚动MKMapView。

override func viewDidLoad() { 
    super.viewDidLoad() 

    manager = CLLocationManager() 
    manager.delegate = self  
    manager.desiredAccuracy = kCLLocationAccuracyBest 
    manager.requestAlwaysAuthorization()     
    manager.startUpdatingLocation()      

    theMap.delegate = self 
    theMap.mapType = MKMapType.Standard 
    theMap.zoomEnabled = true   
    theMap.addGestureRecognizer(longPress) 
    theMap.scrollEnabled = true 

} 

func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) { 

    let spanX = 0.007 
    let spanY = 0.007 
    var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY)) 
    theMap.setRegion(newRegion, animated: false) 
    theMap.scrollEnabled = true 

} 

如果我滚动地图,1秒后,我返回到用户的位置。我应该改变setRegion方法的位置吗?

+0

MKCoordinateRegion(中心:这theMap.userLocation.coordinate将返回给用户位置..... –

回答

0

您需要检测何时滚动地图,可能是通过执行MKMapViewDelegate中定义的mapView(_:regionWillChangeAnimated:)方法。在这种方法中,您需要将地图视图的userTrackingMode属性设置为.None。当用户平移或缩放变量时,您的实现将被调用。因此,您应该努力保持实现尽可能轻量级,因为可以多次调用单个平移或缩放手势。

func mapView(mapView: MKMapView!, regionWillChangeAnimated animated: Bool) { 
    if you want to stop tracking the user { 
     mapView.userTrackingMode = .None 
    } 
} 

当你想重新开始跟随用户的位置,这个属性变回要么.Follow.FollowWithHeading

enum MKUserTrackingMode : Int { 
    case None // the user's location is not followed 
    case Follow // the map follows the user's location 
    case FollowWithHeading // the map follows the user's location and heading 
} 
+0

非常感谢ndmeriri。我解决了我的问题阅读文档。我在locationManager方法中添加了“theMap.setRegion(newRegion,animated:false)”方法,并在其中禁用更新位置时添加了一个地图分支侦听器用manager.stopUpdatingLocation()方法。 谢谢! – user2982520