可视格式语言宽度和高度约束未得到遵守

时间:2014-01-16 20:07:55

标签: ios visual-format-language

我在故事板上设置了这个视图控制器,我需要以编程方式添加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间距是可以的

我是否需要为地图设置初始帧?

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

+ (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;
}

1 个答案:

答案 0 :(得分:0)

今天早上我就把它解决了 初始化地图视图时,我不应该设置自动调整大小。相反,我应该设置:
[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;
}
相关问题