我在故事板上设置了这个视图控制器,我需要以编程方式向它添加一个 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;
}