0

我在故事板上设置了这个视图控制器,我需要以编程方式向它添加一个 MapView。

我希望地图填充视图的宽度,并在两个方向上保持 100 的恒定高度。另外,我希望地图下方的 imageView 的间距为 10。

这是我正在使用的代码。

_map = [MyClass sharedMap]; // Get singleton
[_map removeFromSuperview]; // Remove from the other VC view
[_map removeConstraints:[_map constraints]]; // Remove constraints if any
[[self view] addSubview:_map];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_map]|" options:0 metrics:nil views:@{@"_map" : _map}]];
[[self view] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_map(100)]-10-[_sellerImage]" options:0 metrics:nil views:@{@"_map" : _map, @"_imageView" : _imageView}]];

但结果是:

  • 宽度是恒定的,不填充屏幕宽度
  • 纵向时高度会增加
  • 到 imageView 的 10 px 间距是可以的

我需要为地图设置初始框架吗?

此地图视图是在许多视图中使用的单例,以节省内存。这是它的初始化代码:

+ (MKMapView *)sharedMap {
  static MKMapView *mapView;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    mapView = [[MKMapView alloc] init];
    if (IS_IOS_7) {
      [mapView setShowsUserLocation:YES];
      [mapView setPitchEnabled:NO];
    }
    [mapView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
  });

  return mapView;
}
4

1 回答 1

0

我今天早上很早就解决了这个问题。
当我初始化地图视图时,我不应该设置 Autoresize Mask。相反,我应该设置:
[mapView setTranslatesAutoresizingMaskIntoConstraints:NO];

只需为地图视图设置一次框架。我选择在初始化期间设置它。之后,约束和 VFL 控制其位置和尺寸。所有错误都消失了,它完全按照我的意愿工作。

作为记录,这是完整的初始化方法:

+ (MKMapView *)sharedMap {
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    mapView = [[MKMapView alloc] init];
    [mapView setFrame:CGRectMake(0, 0, 1, 1)];

    // Configure the map view
    if (IS_IOS_7) {
      [mapView setShowsUserLocation:YES];
      [mapView setPitchEnabled:NO];
    }
    [mapView setTranslatesAutoresizingMaskIntoConstraints:NO];
  });

  return mapView;
}
于 2014-01-17T14:19:29.323 回答