你可以做的是在你的視圖控制器中實現MKMapViewDelegate
協議,當你的疊加被添加時,它給你回調。您可以實現一種只繪製一條線段(兩點)的方法,並且每當您被通知已添加另一條線條疊加時觸發該方法。
聲明一些實例變量在您的視圖控制器:
@interface ViewController : UIViewController<MKMapViewDelegate> {
@private
MKMapView* mapView;
CLLocationCoordinate2D coordinates[4];
int lineNumber;
BOOL isPaused;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapView;
然後在您的視圖控制器.m文件:
- (void)addNextLine {
if (!isPaused) {
// move to the next line
lineNumber++;
MKPolyline* line = [MKPolyline polylineWithCoordinates: &coordinates[lineNumber - 1]
count: 2];
[self.mapView addOverlay: line];
}
}
- (void)drawPolylines {
isPaused = NO;
// initialize the list of coordinates for the line segments
coordinates[0] = CLLocationCoordinate2DMake(47.8, -122.0);
coordinates[1] = CLLocationCoordinate2DMake(47.9, -122.0);
coordinates[2] = CLLocationCoordinate2DMake(47.9, -122.1);
coordinates[3] = CLLocationCoordinate2DMake(48.0, -122.1);
lineNumber = 0;
self.mapView.region = MKCoordinateRegionMake(coordinates[0], MKCoordinateSpanMake(0.2, 0.2));
// start adding lines one at a time
[self addNextLine];
}
// MKMapViewDelegate callback when an overlay has been added
- (void)mapView:(MKMapView *)theMap didAddOverlayViews:(NSArray *)overlayViews {
if (lineNumber < 3) {
// schedule the next line segment to be drawn after a 2 second delay:
[self performSelector: @selector(addNextLine) withObject:nil afterDelay: 2.0f];
}
}
// MKMapViewDelegate callback when an overlay's view needs to be generated
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
if ([[overlay class] isSubclassOfClass: [MKPolyline class]]) {
MKPolylineView* view = [[MKPolylineView alloc] initWithPolyline: overlay];
view.strokeColor = [UIColor redColor];
view.lineWidth = 2;
view.fillColor = [UIColor redColor];
return view;
}
return nil;
}
可以觸發整個過程通過調用啓動:
[self drawPolylines];
在我的代碼中,它有每條線之間的延遲時間爲2秒。刪除/更改,如果你喜歡。
編輯:爲了啓動和暫停的按鈕的過程中,你的UIButton
■連接到這些行動:
-(IBAction)onStart: (id)sender {
if (isPaused) {
isPaused = NO;
[self addNextLine];
} else {
[self drawPolylines];
}
}
-(IBAction)onPause: (id)sender {
isPaused = YES;
}