iOS - MKMapView showAnnotations:animated: with padding?

后端 未结 4 1975
春和景丽
春和景丽 2020-12-14 21:53

I want to be able to zoom my MKMapView to fit it\'s annotations. I have managed to do it using iOS7\'s showAnnotations method. But I would also like to add some

4条回答
  •  温柔的废话
    2020-12-14 22:44

    You are doing it the right way. Try changing the padding, you'll see the difference.

    Other way, there must be something else in your code preventing from changing the view

    EDIT: I was totally wrong. Try this:

    Create an instance variable

    BOOL _mapNeedsPadding;
    

    and initialize it to NO;

    Then set your mapView delegate to self and add a to your class header

    Then add this to your class

    - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
        if(_mapNeedsPadding){
            _mapNeedsPadding = NO;
            [self.mapView setVisibleMapRect:self.mapView.visibleMapRect edgePadding:UIEdgeInsetsMake(100, 20, 10, 10) animated:YES];
        }
    }
    

    And finally call your showAnnotations function like this:

    _mapNeedsPadding = YES;
    [self.mapView showAnnotations:annotations animated:YES];
    

    The showAnnimation will trigger the regionDidChangeAnimated function. You need to set _mapNeedsPadding to NO after changing visibleMapRect because this function (setVisibleMapRect:self) will also trigger regionDidChangeAnimated.

    Hope this helps !

提交回复
热议问题