根据从xib文件

时间:2017-09-12 11:27:39

标签: ios swift uiview uiviewcontroller

我有xib文件,其高度可以动态更改,因为它包含多行标签。我需要将此视图添加为在我的视图控制器中定义的uiview的子视图。

let settlementDetailsContentView = SettlementDetailsView.instanceFromNib(nibNamed: NibConstants.SettlementDetailsViewNib)
settlementDetailsContentView.frame = settlementDetailsView.bounds
settlementDetailsView.addSubview(settlementDetailsContentView)

这里的settlementDetailsContentView包含在Interface中设计的视图 建设者。 settlementDetailsView是我的视图控制器中定义的视图,其高度约束大于或等于零。

下面的代码是根据笔尖名称

返回视图的函数
 class func instanceFromNib(nibNamed : String) -> SettlementDetailsView
 {
     return UINib(nibName: nibNamed, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! SettlementDetailsView
 }

我所做的问题是,resolvedetails视图下面的视图与此重叠,因为视图高度没有根据子视图调整大小。

  

这是UI的外观。重叠的文件重叠   settlementDetails视图。

This is how the view looks.

  

这就是uiview的样子

enter image description here

1 个答案:

答案 0 :(得分:1)

问题在于您没有更改settlementDetailsView的框架。在以下代码中

let settlementDetailsContentView = SettlementDetailsView.instanceFromNib(nibNamed: NibConstants.SettlementDetailsViewNib)
settlementDetailsView.addSubview(settlementDetailsContentView)
settlementDetailsContentView.translatesAutoresizingMaskIntoConstraints = false
settlementDetailsContentView.topAnchor.constraint(equalTo: settlementDetailsView.topAnchor).isActive = true
settlementDetailsContentView.bottomAnchor.constraint(equalTo: settlementDetailsView.bottomAnchor).isActive = true
settlementDetailsContentView.trailingAnchor.constraint(equalTo: settlementDetailsView.trailingAnchor).isActive = true
settlementDetailsContentView.leadingAnchor.constraint(equalTo: settlementDetailsView.leadingAnchor).isActive = true

您约束子视图增长到superView的完整大小,或者superView缩小到子视图的大小(这取决于superview的约束和两者的拥抱/压缩,但应该给你的愿望效果)。

请参阅autolayout参考

修改

现在您已经发布了它应该如何显示,以下代码实现了:

let superView = settlementDetailsView.superview!
let settlementDetailsContentView = SettlementDetailsView.instanceFromNib(nibNamed: NibConstants.SettlementDetailsViewNib)
superview.addSubview(settlementDetailsContentView)
settlementDetailsContentView.translatesAutoresizingMaskIntoConstraints = false
settlementDetailsContentView.topAnchor.constraint(equalTo: settlementDetailsView.bottomAnchor).isActive = true
settlementDetailsContentView.bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
settlementDetailsContentView.trailingAnchor.constraint(equalTo: superview.trailingAnchor).isActive = true
settlementDetailsContentView.leadingAnchor.constraint(equalTo: superview.leadingAnchor).isActive = true

请注意,如果settlementDetailsView对其superView有一个底部约束,则应将其停用。