[英]Adding view controller to uiview with constraints
在情節提要中,我有3個屏幕(控制器視圖):1)控制器“ main”包含名為cntdetail的uiview和名為viewswitch的按鈕2)控制器“ A”具有多個元素(標簽,文本字段...)3)控制器“ B”也有幾個元素
我需要什么來在視圖出現時以cntdetail加載視圖A並在點擊按鈕時從A切換到B,反之亦然。
我在做什么(在C#中,但幾乎像swift一樣):
在主ViewDidLoad中:
cviewA = Storyboard.InstantiateViewController("SaisieVocale");
cviewB = Storyboard.InstantiateViewController("SaisieDetaillee");
AddChildViewController(cviewA);
AddChildViewController(cviewB);
viewAcontenth = GetContentHeight(cviewA.View); //a personal function that calculate the height of the content, it works
viewBcontenth = GetContentHeight(cviewB.View);
單擊按鈕時(與viewdidappear中的按鈕幾乎相同)(我使用A來簡化,但一次是A一次是B):
cviewB.View.RemoveFromSuperview();
//change the height constraint of the uiview to fit the height of my views
foreach (var cst in cntdetails.Constraints)
{
if ((UIView)cst.FirstItem == cntdetails || (UIView)cst.SecondItem == cntdetails)
{
if (cst.FirstAttribute == NSLayoutAttribute.Height) //il faut modifier la contrainte de hauteur
cst.Constant = viewAcontenth;
}
}
cntdetails.AddSubview(cviewA.View);
但這並沒有按預期方式工作,每當我單擊該按鈕時,主視圖的hiehgt都會增加一點,並且其中一個視圖(A或B)不可見。
編輯:cntdetails在頂部,前導,尾隨和高度與主視圖具有相同的約束。 然后,我只需要修改高度約束,然后實際完成此部分即可。
編輯:我試圖添加約束以保持cntdetail的大小之后A和B的大小,但這並不更好:
cviewA.View.TranslatesAutoresizingMaskIntoConstraints = false;
cviewA.View.LeadingAnchor.ConstraintEqualTo(cntdetails.LeadingAnchor).Active = true;
cviewA.View.TrailingAnchor.ConstraintEqualTo(cntdetails.TrailingAnchor).Active = true;
cviewA.View.WidthAnchor.ConstraintEqualTo(cntdetails.WidthAnchor).Active = true;
cviewA.View.HeightAnchor.ConstraintEqualTo(cntdetails.HeightAnchor).Active = true;
最終,我發現了一些錯誤。 此頁面有助於增加主要視圖,這是因為我的功能計算了視圖高度。
首先在viewdidload中:
cviewA = Storyboard.InstantiateViewController("SaisieVocale");
cviewB = Storyboard.InstantiateViewController("SaisieDetaillee");
//AddChildViewController(cviewA); no need to do that here
//AddChildViewController(cviewB);
viewAcontenth = GetContentHeight(cviewA.View); //a personal function that calculate the height of the content, it works
viewBcontenth = GetContentHeight(cviewB.View);
從A切換到B時:
//change the height constraint of the uiview to fit the height of my views
foreach (var cst in cntdetails.Constraints)
{
if ((UIView)cst.FirstItem == cntdetails || (UIView)cst.SecondItem == cntdetails)
{
if (cst.FirstAttribute == NSLayoutAttribute.Height) //il faut modifier la contrainte de hauteur
cst.Constant = viewAcontenth;
}
}
//first remove B except the first time
cviewB.DidMoveToParentViewController(null);
cviewB.View.RemoveFromSuperview();
cviewB.RemoveFromParentViewController();
//next add A:
this.AddChildViewController(cviewA);
cviewA.View.Frame= cntdetails.Bounds;
cntdetails.AddSubview(cviewA.View);
cviewA.DidMoveToParentViewController(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.