2014-01-16 76 views
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}]]; 

但結果是:

  • 寬度是恆定的並且不填充所述屏幕寬度
  • 的高度增加時,它的上縱向朝向
  • 10像素間隔的ImageView的是好吧

我需要爲地圖設置初始框架嗎?

此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; 
} 
+0

很有可能。 – Pavan

+0

在控制檯中是否有任何佈局警告? – jrturton

+0

您可以在創建地圖視圖的位置添加代碼嗎? – jrturton

回答

0

今天早上我做了這個。
當我初始化地圖視圖時,我不應該設置Autoresize遮罩。相反,我應該設置:
[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; 
} 
+0

您可能不需要設置初始幀。關鍵是關閉自動調整。 – jrturton

+0

我以爲我沒有,但然後它會崩潰說'***終止應用程序由於未捕獲的異常'NSInvalidArgumentException',原因:'無效的區域<中心:南,南span:南,南>'' – Guilherme

+0

必須是一個地圖視圖特定的東西,然後用自動佈局,你永遠不會正常設置框架。 – jrturton