2016-12-11 49 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