【问题标题】:Only add pin when button is clicked仅在单击按钮时添加引脚
【发布时间】:2014-05-29 01:02:48
【问题描述】:

我有这段代码需要稍微修改一下。我下面的代码在我当前的位置上创建了一个图钉(正如我可能会添加的那样)。

唯一的问题是我只需要在单击按钮时运行代码,而不是每次移动时运行。

这是当前位置的代码和别针。

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.mapView setDelegate:self];
    [self.mapView setShowsUserLocation:YES];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {

    // zoom to region containing the user location
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 700, 700);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

    // add the annotation
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    point.coordinate = userLocation.coordinate;
    point.title = @"Your Car";
    //point.subtitle = @"";
    [self.mapView addAnnotation:point];
}

当我点击一个按钮时,我需要它运行:

-(IBAction)addPin
{
}

【问题讨论】:

    标签: ios mkmapview mkannotation mkuserlocation


    【解决方案1】:

    在 viewDidLoad: 方法中,

    像这样创建一个按钮:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
           action:@selector(showPinOnClick)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(100.0, 200.0, 150.0, 60.0);
    [self.view addSubview:button];
    

    // 在视图控制器中创建定义为 UIButton 选择器方法的方法

    -(void) showPinOnClick{
    //paste your code here to show the pin
    
    CLLocationCoordinate2D location = self.mapview.userLocation.coordinate;
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    
    location.latitude  = -32.008081;
    location.longitude = 115.757671;
    
    span.latitudeDelta = 0.03;
    span.longitudeDelta = 0.03;
    
    region.span = span;
    region.center = location;
    
    
    [_mapview setRegion:region animated:YES];
    [_mapview regionThatFits:region];
    
    //Create your annotation
    MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
    // Set your annotation to point at your coordinate
    point.coordinate = location;
    
    point.title = @"Your Car";
    
    
    //Drop pin on map
    [_mapview addAnnotation:point];
    [_mapview selectAnnotation:point animated:NO];
    
    }
    

    【讨论】:

    • 问题是当我把我的代码放在 void... 没有声明 userLocation 所以它有错误。
    • 因此,您需要在该方法中自己找到 userLocation 或简单地从其他方法中传递。
    • 好的,请参阅更新的答案,这将带您到达您定义的纬度和经度点
    • 好的,非常感谢!一个错误。由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[ViewController showPinOnClick:]:无法识别的选择器发送到实例 0x15e6100e0”
    • 只需去掉选择器调用行中的分号即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多