I have this view controller set up on a storyboard, and I need to add a MapView to it programmatically.
I want the map to fill the view's width and have a constant height of 100 on both orientations. Also, I want a spacing of 10 to the imageView that's below the map.
This is the code I'm using.
_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}]];
But the results are:
Do I need to set a initial frame for the map?
This mapview is a singleton used in many views in order to save memory. This is its initialization code:
+ (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;
}
I worked this out early this morning.
When I initialize the map view, I shouldn't be setting an Autoresize Mask. Instead I should set:
[mapView setTranslatesAutoresizingMaskIntoConstraints:NO];
It is necessary to set a frame for the map view just once. I opted to set it during its initialization. After that, constraints and VFL take control of its position and dimensions. All errors are gone and it works exactly as I wanted.
For the record, this is the full initialization method:
+ (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;
}