2014-01-15 109 views
0

我有一個大小爲(320,182)的mapView。一旦按下了UIBarButtonItem,我想顯示這個mapView從屏幕頂部向下滑動。爲了達到這個目的,我編寫了這樣的代碼。顯示從頂部向下滑動的半屏視圖

UIBarButtonItem *mapButton = [[UIBarButtonItem alloc] 
           initWithImage:[UIImage imageNamed:@"map_1.png"] 
           style:UIBarButtonItemStylePlain 
           target:self 
           action:@selector(showMap:) 
           ]; 
    self.navigationItem.rightBarButtonItem = mapButton; 


    -(void)showMap:(id)sender{ 
     self._mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,-182,320,182)]; 
     [self.scrollView addSubview:self._mapView]; 

     //show view 
     [UIView beginAnimations:nil context:NULL]; 
     [UIView setAnimationBeginsFromCurrentState:YES]; 
     [UIView setAnimationDuration:1.0]; 
     CGRect rect = [self._mapView frame]; 
     rect.origin.y = 0; 
     [self._mapView setFrame:rect]; 
     [UIView commitAnimations]; 
    } 

這將顯示從屏幕頂部向下滑動的地圖視圖。但是,如何在第二次按UIBarButtonItem時使mapView關閉?此外,我還想在mapView外部點擊時關閉mapView。

回答

2

這是一個變化的你所要求的基本實現。但它會做到這一點。

#import "ViewController.h" 
#import "MKMapView.h" 

@interface ViewController() { 
    MKMapView *mapView; 
    BOOL showingMap; 
} 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // 
    UIBarButtonItem *mapButton = [[UIBarButtonItem alloc] 
            initWithTitle:@"Map" 
            style:UIBarButtonItemStylePlain 
            target:self 
            action:@selector(toggleMap:) 
            ]; 
    self.navigationItem.rightBarButtonItem = mapButton; 

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissView:)]; 
    [self.view addGestureRecognizer:tapRecognizer]; 
} 

-(void)toggleMap:(id)sender{ 
    if (!mapView) { 
     mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,-182,320,182)]; 
     mapView.backgroundColor = [UIColor redColor]; // red background for testing 
     [self.view addSubview:mapView]; 
    } 

    CGRect rect = mapView.frame; 
    rect.origin.y = showingMap ? -rect.size.height : 0; 

    showingMap = !showingMap; 

    [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{ 
     mapView.frame = rect; 
    } completion:^(BOOL finished) { 

    }]; 
} 

- (void)dismissView:(UITapGestureRecognizer*)recognizer { 
    // bail out since map isn't showing 
    if (!showingMap) return; 

    CGPoint pt = [recognizer locationInView:self.view]; 
    UIView *v = [self.view hitTest:pt withEvent:nil]; 

    if (![v isKindOfClass:[MKMapView class]]) { 
     NSLog(@"dismiss"); 
     [self toggleMap:nil]; 
     return; 
    } 
} 

@end 
+0

它的工作!的確非常感謝你的幫助。 – kenken

0

只是扭轉動畫(你應該在更現代的方法塊做):

rect.origin.y = -182; 
[UIView animateWithDuration:1.0 animations^{ 
    self.mapView.frame = rect; 
} 
相關問題