2016-12-11 72 views
1

我有一個自定義視圖,下面有兩個標籤。視圖init方法看起來像這樣iOS自定義視圖 - 帶CGRect.zero的初始化 - 約束警告

self.locationView = LocationView(frame: CGRect.zero) 

對於子視圖定位主視圖中,我使用下面的限制內:

 self.gMapsView.addConstraints(
     NSLayoutConstraint.constraints(
      withVisualFormat: "H:|-[locationView]-|", 
      options: NSLayoutFormatOptions(rawValue: UInt(0)), 
      metrics: nil, 
      views: views 
     ) 
    ) 

    self.gMapsView.addConstraints(
     NSLayoutConstraint.constraints(
      withVisualFormat: "V:[locationView]-(paddingBottom)-|", 
      options: NSLayoutFormatOptions(rawValue: UInt(0)), 
      metrics: [ 
       "paddingBottom": LOCATION_VIEW_CONFIG.paddingBottom 
      ], 
      views: views 
     ) 
    ) 

對於標籤定位我使用下面的約束位置的視圖內:

 self.addConstraints(
     NSLayoutConstraint.constraints(
      withVisualFormat: "H:|[streetLabel]|", 
      options: NSLayoutFormatOptions(rawValue: UInt(0)), 
      metrics: nil, 
      views: views 
     ) 
    ) 

    self.addConstraints(
     NSLayoutConstraint.constraints(
      withVisualFormat: "H:|[cityLabel]|", 
      options: NSLayoutFormatOptions(rawValue: UInt(0)), 
      metrics: nil, 
      views: views 
     ) 
    ) 

    self.addConstraints(
     NSLayoutConstraint.constraints(
      withVisualFormat: "V:|-[streetLabel]-[cityLabel]-|", 
      options: NSLayoutFormatOptions(rawValue: UInt(0)), 
      metrics: nil, 
      views: views 
     ) 
    ) 

不幸的是我得到的約束警告:

(
"<NSAutoresizingMaskLayoutConstraint:0x608000280820 h=--& v=--& Test.LocationView:0x7fdc40f0c780.height == 0 (active)>", 
"<NSLayoutConstraint:0x608000280190 UILabel:0x7fdc40f0cb40.top == Test.LocationView:0x7fdc40f0c780.topMargin (active)>", 
"<NSLayoutConstraint:0x608000280320 V:[UILabel:0x7fdc40f0cb40]-(NSSpace(8))-[UILabel:0x7fdc40d155e0] (active)>", 
"<NSLayoutConstraint:0x6080002802d0 Test.LocationView:0x7fdc40f0c780.bottomMargin == UILabel:0x7fdc40d155e0.bottom (active)>" 
) 

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x608000280320 V:[UILabel:0x7fdc40f0cb40]-(NSSpace(8))-[UILabel:0x7fdc40d155e0] (active)> 

我該如何解決它們?非常感謝:)

回答

0

您需要關閉Autoresizing Mask,這是第一個列出的約束(NSAutoresizingMaskLayoutConstraint),與之後創建的約束衝突。您可以看到它將高度設置爲0.添加:

self.locationView.translatesAutoresizingMaskIntoConstraints = NO;

您的佈局可能還有其他問題,但應該解決衝突。

+0

非常感謝!我已經有了這些代碼,但是在將視圖添加到父視圖後調用了它。 – user3532505