問題描述
即使這里有多個問題和答案,我也無法創建具有靜態和動態內容的 UIScrollView
(通過使用 ContainerView
)和使尺寸正常工作.因此,我將提供分步指南,直到我無法取得任何進展并且有人可以提供解決方案.這樣我們就有了一個可行的示例,可以一步一步地進行操作.
請注意:所有步驟的輸出都上傳到
第 4 步:運行應用:
運行應用程序并一直滾動到底部,包括反彈區域,結果如下:
由此我們可以得出結論:
ContainerView
的位置正確(即在SecondLabel
和BottomLabel
之間),但BottomLabel
正確不遵守其低于ContainerView
的約束.TableView
的高度明顯是0.這也是因為沒有調用func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
.如果我們在TableView
上設置高度限制,項目就會顯示出來.- 如果
ContainerView
的大小增加,ScrollView
的內容大小不會增加. - 還希望在動態
TableView
中始終顯示 所有 項,并像它們只是ScrollView 中的靜態數據一樣滾動過去
. - 這東西真是亂七八糟.
第 5 步:問題!
- 我們怎樣才能讓
ScrollView
的內容正確地包裹所有的內容,包括TableView
中的動態數據在ContainerView
中? - 約束設置是否正確?
- 我們應該在哪里以及如何計算合適的高度/內容大小?
- 這一切真的有必要嗎?有沒有更簡單的方法來實現這一點?
第 6 步:在@agibson007 的回答之后修復解決方案:
像這樣添加
static let CELL_HEIGHT = 44
:導入 UIKit類 TableViewCell : UITableViewCell {@IBOutlet 弱變量數據標簽:UILabel!靜態讓 CELL_HEIGHT = 44}
將
TableView
的固有大小從Placeholder
恢復為Default
.- 在
TableView
上設置高度限制,例如 150.該值必須大于一個單元格的高度. - 將高度約束添加到
DynamicEmbeddedViewController
作為IBOutlet
. 添加代碼來計算和設置
TableView
高度約束.最后一課:導入 UIKit類 DynamicEmbeddedViewController : UIViewController, UITableViewDataSource, UITableViewDelegate{@IBOutlet 弱 var tableView:UITableView!@IBOutlet 弱 var tableViewHeight:NSLayoutConstraint!讓數據= [第一",第二",第三",第四",第五",第六",最后"]覆蓋 func viewDidLoad() {super.viewDidLoad()tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")//調整我們的約束讓 totalHeight = data.count * TableViewCell.CELL_HEIGHTtableViewHeight.constant = CGFloat(totalHeight)self.updateViewConstraints()//在一個真實的應用程序中,一個委托回調會很好地更新滾動視圖上的約束}func numberOfSections(in tableView: UITableView) ->詮釋{返回 1}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->詮釋{返回數據.count}func tableView(_tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {讓 cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as!表視圖單元格cell.dataLabel.text = 數據[indexPath.row]返回單元格}}
將
ContainerView
的固有大小從Placeholder
恢復為Default
.- 在
ContainerView
上設置高度限制,例如 150.此值將在代碼中更新. - 將高度約束添加到
ContainerView
作為FirstViewController
中的IBOutlet
. - 將
ContainerView
添加為FirstViewController
中的IBOutlet
. - 在
FirstViewController
中創建對DynamicEmbeddedViewController
的引用,以便在計算高度時引用它. 添加代碼來計算和設置
ContainerView
高度約束.最終的FirstViewController 類: 導入 UIKit類 FirstViewController: UIViewController {@IBOutlet 弱 var containerView:UIView!@IBOutlet 弱變量 containerViewHeightConstraint:NSLayoutConstraint!var dynamicView: DynamicEmbeddedViewController?覆蓋 func viewDidLoad() {super.viewDidLoad()//在加載視圖后做任何額外的設置,通常是從一個 nib.如果動態視圖!= nil{動態視圖?.tableView.reloadData()讓 size = dynamicView?.tableView.contentSize.height//在 300 上作弊,因為該控制器中的其他視圖每個 150containerViewHeightConstraint.constant = 大小!+ 300self.view.updateConstraintsIfNeeded()}}覆蓋 func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()//處理所有可以重新創建的資源.}覆蓋函數準備(對于segue:UIStoryboardSegue,發件人:任何?){if (segue.identifier == "ContainerViewSegue") {dynamicView = segue.destination 作為?DynamicEmbeddedViewController}}
}
最后一切都按預期進行!
請注意:所有步驟的輸出都上傳到
現在將 UILabel 拖到滾動視圖上并快速查看警告.ScrollView 模糊的可滾動內容(寬度和高度).
現在為所有人添加一個頂部、底部、前導和尾隨 20.
沒有警告.
測試 2)刪除 UILabel 并將 UIView 拖到滾動視圖上并添加頂部、底部、前導和尾隨,例如 20.
警告!警告!警告!
問題在于 UIView 無法調整自身大小,并且滾動視圖不知道其內容有多大,因此無法設置.
<小時>如果這有意義 == 真繼續別的返回
現在根據我們的進展情況,它會變得更加復雜,但上面的概念支配著整個過程.
調查您的項目和設置,您在學習 UIScrollview 方面做得很好.
現在讓我們回顧一下你的總結,我會就一些事情發表評論.
根據您上面的報價
由此我們可以得出結論:ContainerView 的位置是正確的(即在 SecondLabel 和 BottomLabel 之間),但 BottomLabel 不遵守其低于 ContainerView 的約束."
***-> 你這里的總結其實是不正確的.轉到標簽上方的容器并在界面生成器中選中剪輯到邊界并重新運行項目,標簽將在底部,但不會有綠色視圖.為什么?它不知道它應該有多大.當你在它加載之前運行它時它可以并且 uilabels 是清晰的,所以當它超出它的邊界時它看起來不正確.
"TableView的高度明顯是0,這也是因為沒有調用func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath),如果我們給TableView設置了高度約束,item就會出現.
***-> 這是最難處理的.您必須加載 tableview 并獲取 tableview 內容大小并在代碼中更新 tableview 的高度約束以使其更新,以便滾動視圖調整容納控制器的容器的大小.
如果它包含的內容具有內在的內容大小,則可以使用 stackview 來確定它的高度和寬度.
但回到表格視圖.您需要在 tableview//您的行高上設置 >= 40 才能從動態視圖開始.如果計數為 0,則檢查數據源后,您會將約束更新為 0 并使用委托讓滾動視圖知道更新它對動態視圖控制器的約束以不顯示表.我希望這是有道理的.然后相反,如果計數是數據源中的 10 個項目,則將 dynamicviewcontroller tableview 高度約束的約束更新為 10 * 40,就像這樣
導入 UIKit類 DynamicEmbeddedViewController : UIViewController, UITableViewDataSource, UITableViewDelegate{@IBOutlet 弱 var tableViewConstraint:NSLayoutConstraint!@IBOutlet 弱 var tableView:UITableView!讓數據= [第一",第二",第三",第四",第五",第六",最后"]覆蓋 func viewDidLoad() {super.viewDidLoad()tableView.delegate = 自我tableView.dataSource = 自我tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")//調整我們的約束讓 count = data.count讓常數 = 計數 * 40tableViewConstraint.constant = CGFloat(常數)self.updateViewConstraints()//在一個真實的應用程序中,一個委托回調會很好地更新滾動視圖上的約束}
在第一個控制器中它看起來像這樣.
導入 UIKit類 FirstViewController: UIViewController {@IBOutlet 弱變量 containerViewHeightConstraint:NSLayoutConstraint!@IBOutlet 弱 var containerView:UIView!@IBOutlet 弱變量滾動視圖:UIScrollView!var dynamicView : DynamicEmbeddedViewController?覆蓋 func viewDidLoad() {super.viewDidLoad()//在加載視圖后做任何額外的設置,通常是從一個 nib.如果動態視圖!= nil{動態視圖?.tableView.reloadData()//獲取大小讓 size = dynamicView?.tableView.contentSize.height//在 300 上作弊,因為我看到您將該控制器中的其他視圖設置為每個 150containerViewHeightConstraint.constant = 大小!+ 300self.view.updateConstraintsIfNeeded()}}覆蓋 func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()//處理所有可以重新創建的資源.}覆蓋函數準備(對于segue:UIStoryboardSegue,發件人:任何?){if (segue.identifier == "ContainerViewSegue") {dynamicView = segue.destination 作為?DynamicEmbeddedViewController}}}
你可以看到我們調整了所有東西的大小以適應.除此之外,你做對了.現在到生產有價值的代碼.大多數時候,您會知道將顯示哪些內容,以便您可以控制它.另一種方法是對所有內容使用 UITableView 或 UICollectionView,并根據內容加載不同的單元格.我希望這篇文章能澄清一點.我相信我們可以繼續添加它,但希望所涵蓋的概念就足夠了.如果這回答了您的問題,請對這樣做所花費的時間表示一些愛.如果你愿意,我也可以將它上傳到 GitHub,但最好放在你開始的 repo 中.
Even though there are multiple questions and answers to this questions here on SO I just cannot create a UIScrollView
with both static and dynamic content (by using a ContainerView
) and make the sizes work properly. I will therefore provide a step by step guide until the point where I cannot make any progress and someone can provide a solution. This way we will have a workable sample that can be followed step by step to make it work.
Please note: The output from all of the steps is uploaded to https://github.com/oysteinmyrmo/DynamicScrollablePage for convenience. The test Xcode project can be fetched from there and hacked on further.
Update: After @agibson007's answer, there are a few steps at the end to fix the original steps to a working solution. Errors are noted by stating ERROR, SEE FINAL STEPS.
Goal:
Have a long scrollable UIView
page with various static UIView
s and a ContainerView
with dynamic content. For completeness' sake the dynamic content will consist of some static UIView
s and a UITableView
that will be expanded to its entire contents. The last element seems to be a reoccurring theme in the various questions I have stumbled upon lately.
Method:
- We will start with a new Xcode project (Xcode 8.2.1) and use Swift 3.0.2 as language.
- We will step by step create test
UIView
s,UIViewController
s and other required items. - At some point we have a "template" that can be used to make the content expand dynamically by someone who are able.
Step 1: Project Creation
Open Xcode (8.2.1), start a new project.
- Select Tabbed Application. We will create the
UIScrollView
in the first tab. - Set product name to DynamicScrollablePage.
- Select location and create the project.
Step 2: Initial Changes to the Project
The changes to the UI will be done in the first tab. The procedure is heavily influenced by this answer, but we will add a couple of more items and a ContainerView
for our dynamic content.
- In
Main.storyboard
,First View
(i.e. tab 1) delete the two labels. - Click the
UIViewController
(named first). Go to its size inspector, change fromFixed
toFreeform
and change the height to 1500. This is only a visual change in the storyboard. - Rename the remaining
UIView
asRootView
. - Add a
UIScrollView
insideRootView
. Name itScrollView
. Constraints:- ScrollView[Top, Bottom, Leading, Trailing, Width] = RootView[Top, Bottom, Leading, Trailing, Width]. In my experience the width constraint must also be set to ensure covering the entire screen later on.
- Add a
UIView
insideScrollView
and name itContentView
. Constraints:- ContentView[Leading, Trailing, Top, Bottom, Width] = ScrollView[Leading, Trailing, Top, Bottom, Width]. The storyboard will now complain about scrolling height. It will not complain after the steps below.
- Add items to
ContentView
:- First add a
UIView
, name itRedView
. SetRedView
[Leading, Trailing, Top] =ContentView
[Leading, Trailing, Top]. SetRedView
[Height, Background Color] = [150, Red]. - Add a
UILabel
belowRedView
, set its name/text toFirstLabel
. SetFirstLabel
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetFirstLabel
[Top] =RedView
[Bottom]. - Add a
UIView
belowFirstLabel
, name itBlueView
. SetBlueView
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetBlueView
[Top] =FirstLabel
[Bottom]. SetBlueView
[Height, Background Color] = [450, Blue]. - Add a
UILabel
belowBlueView
, set its name/text toSecondLabel
. SetSecondLabel
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetSecondLabel
[Top] =BlueView
[Bottom]. - Add a
UIContainerView
belowSecondLabel
, name itContainerView
. SetContainerView
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetContainerView
[Top] =SecondLabel
[Bottom]. SetContainerView
[Intrinsic size] = [Placeholder] (see Size inspector for theContainerView
). Setting the intrinsic size to placeholder tells Xcode that the size of it is defined by its child views (as far as I understand). ERROR, SEE FINAL STEPS - Add a
UILabel
at the end, name itBottomLabel
. SetBottomLabel
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetBottomView
[Top] =ContainerView
[Bottom]. - Finally, control + drag from
ScrollView
toBottomView
and selectBottom Space to ScrollView
. This will ensure that theScrollView
's height is correct.
- First add a
Step 3: Create a ViewController with Dynamic Content
Now we will create the actual UIViewController
and xib
file that will be used to display the dynamic contents. We will create a UITableView
inside the xib
and thus we will also need a UITableViewCell
with a simple label for simplicity.
Create a Swift file,
TableViewCell.swift
with the contents:import UIKit class TableViewCell : UITableViewCell { }
Create a
xib
/View
file, namedTableViewCell.xib
. Do the following:- Remove the default
UIView
and replace it with aUITableViewCell
. - Add a
UILabel
to that cell, name itDataLabel
(it will also add a content viewUIView
). - Set
UITableViewCell
's custom class toTableViewCell
. - Set the Table View Cell identifier to
TableViewCellId
. In dual-view mode, ctrl+drag the label to the
TableViewCell
class. The result should be:import UIKit class TableViewCell : UITableViewCell { @IBOutlet weak var dataLabel: UILabel! }
- Remove the default
Create a file
DynamicEmbeddedViewController.swift
with the contents:import UIKit class DynamicEmbeddedViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let data = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Last"] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell") } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell cell.dataLabel.text = data[indexPath.row] return cell } }
Create a
xib
/View
file, namedDynamicEmbeddedView.xib
. Rename the mainUIView
toContentView
and add three items within theContentView
:- Add a
UIView
, name itGreenView
. SetGreenView
[Leading, Trailing, Top] =ContentView
[Leading, Trailing, Top]. SetGreenView
[Height] = [150]. - Add a
UITableView
, name itTableView
. SetTableView
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetTableView
[Top] =GreenView
[Bottom]. Set Intrinsic size = Placeholder. I am not sure if this is the correct approach. ERROR, SEE FINAL STEPS - Add a
UIView
belowTableView
, name itPurpleView
. SetPurpleView
[Leading, Trailing] =ContentView
[Leading, Trailing]. SetPurpleView
[Top] =TableView
[Bottom]. - Note: At this point we might need some more constraints in the xib, but I am unsure what and how, if any.
- Set the
File's Owner
's custom class toDynamicEmbeddedViewController
. - Set the
File's Owner
's View outlet toContainerView
. - Set the
TableView
's dataSource and delegate toFile's Owner
. - Add the
IBOutlet
of theTableView
to theDynamicEmbeddedViewController
class.
- Add a
Connect the created
xib
andUIViewController
in theMain.storyboard
.- Set the Custom Class of the
ContainerView
's output View Controller toDynamicEmbeddedViewController
. - Delete the existing
View
in theContainerViews
output View Controller. I am not sure if this is really needed.
- Set the Custom Class of the
Images of Current Situation:
Step 4: Running the app:
Running the app and scrolling all the way to the bottom, including bounce area, this is the result:
From this we can conclude:
- The position of the
ContainerView
is correct (i.e. betweenSecondLabel
andBottomLabel
), but theBottomLabel
does not adhere its constraint to be below theContainerView
. - The
TableView
's height is obviously 0. This can also be seen sincefunc tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
is not called. If we set a height constraint on theTableView
, items will show up. - The content size of the
ScrollView
does not increase if the size of theContainerView
increases. - It is also desired to display all items in the dynamic
TableView
at all time and just scroll past them as if they were just static data in theScrollView
. - This thing is really messy.
Step 5: The questions!
- How can we make the
ScrollView
's content properly wrap all the contents, including the dynamic data in theTableView
living inside theContainerView
? - Are the constraints set up properly?
- Where and how should we calculate the proper heights/content sizes?
- Is all of this really necessary; are there easier ways to achieve this?
Step 6: Fixing the solution after @agibson007's answer:
Add
static let CELL_HEIGHT = 44
like this:import UIKit class TableViewCell : UITableViewCell { @IBOutlet weak var dataLabel: UILabel! static let CELL_HEIGHT = 44 }
Revert
TableView
's intrinsic size toDefault
fromPlaceholder
.- Set height constraint of for example 150 on the
TableView
. This value must be greater than one cell's height. - Add the height constraint to the
DynamicEmbeddedViewController
as anIBOutlet
. Add code to calculate and set
TableView
height constraint. Final class:import UIKit class DynamicEmbeddedViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewHeight: NSLayoutConstraint! let data = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Last"] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell") // Resize our constraint let totalHeight = data.count * TableViewCell.CELL_HEIGHT tableViewHeight.constant = CGFloat(totalHeight) self.updateViewConstraints() //in a real app a delegate call back would be good to update the constraint on the scrollview } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell cell.dataLabel.text = data[indexPath.row] return cell } }
Revert
ContainerView
's intrinsic size toDefault
fromPlaceholder
.- Set height constraint of for example 150 on the
ContainerView
. This value will be updated in code. - Add the height constraint to the
ContainerView
as anIBOutlet
in theFirstViewController
. - Add the
ContainerView
as anIBOutlet
in theFirstViewController
. - Create reference to the
DynamicEmbeddedViewController
inFirstViewController
so that it may be referenced for height calculation. Add code to calculate and set
ContainerView
height constraint. FinalFirstViewController
class:import UIKit class FirstViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var containerViewHeightConstraint: NSLayoutConstraint! var dynamicView: DynamicEmbeddedViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if dynamicView != nil{ dynamicView?.tableView.reloadData() let size = dynamicView?.tableView.contentSize.height //cheating on the 300 because the other views in that controller at 150 each containerViewHeightConstraint.constant = size! + 300 self.view.updateConstraintsIfNeeded() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "ContainerViewSegue") { dynamicView = segue.destination as? DynamicEmbeddedViewController } }
}
And finally everything works as expected!
Please note: The output from all of the steps is uploaded to https://github.com/oysteinmyrmo/DynamicScrollablePage for convenience. The test Xcode project can be fetched from there and hacked on further.
I am sure this has been answered before but I cannot remember if it has been answered down to why people have so much trouble with a scrollview. It comes down to 2 things that you have to know about UIScrollView and Autolayout.
1) The scrollview needs to be able to calculate the width and height of the content that is inside. This helps with deciding if it actually needs to scroll.
2) Some views have a size based on the content inside. Example a UILabel has an "intrinsic" content size. That means if you drag it out onto the storyboard you do not need to set a height or width unless you are trying to constraint it someway. Other examples of views with intrinsic sizes would be a UIButton, UIImageView(if it has an image), UITextView(with scrolling disabled) and other controls that may have text or images in them.
So let's start really simple and drag a UIScrollView onto the storyboard and pin it to the superview. All is good no warnings.
Now drag a UILabel onto the scrollview and take a quick peak at the warnings. ScrollView ambiguous scrollable content(width and height).
Now add a top, bottom,leading, and trailing of 20 for all.
No warnings.
Test 2) Delete the UILabel and drag a UIView onto the scrollview and add top,bottom,leading,and trailing of say 20.
Warning! Warning! Warning!
The problem is that a UIView does not have the ability to size itself and the scrollview does not know how big its content will be so it cannot setup.
IF THIS MAKES SENSE == True continue ELSE goBack
Now here is where it will get more complex depending on how far we go but the concepts above govern the entire process.
Investigating your project and setup you did pretty well to be learning UIScrollview.
Now lets go over your summary and I will comment in line as to some things.
From your quote above
"From this we can conclude: The position of the ContainerView is correct (i.e. between SecondLabel and BottomLabel), but the BottomLabel does not adhere its constraint to be below the ContainerView."
***-> You summary here is actually incorrect. Go to the container above the label and checkmark clip to bounds in interface builder and re run the project and the label will be at the bottom but there will be no green view. Why? It does not know how big it is supposed to be. When you ran it before it loaded best it could and uilabels are clear so when it went outside its bounds it looked like it was not correct.
"The TableView's height is obviously 0. This can also be seen since func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) is not called. If we set a height constraint on the TableView, items will show up."
***-> This is the trickiest to deal with. You would have to load the tableview and get the tableview content size and update a height constraint on the tableview in code to get it to update for the scrollview to resize for the container that is holding the controller.
An alternative would be a stackview that can determine it's height and width if the content it holds has intrinsic content size.
But back to the tableview. You would need to set a >= 40 on the tableview//your row height to start on the dynamic view. After you check your datasource if the count is 0 you would update the constraint to 0 and use a delegate to let the scrollview know to update it's constraint on the dynamicviewcontroller to not show the table. I hope this makes sense. Then conversely if the count is say 10 items in the datasource update the constraint on both the dynamicviewcontroller tableview height constraint to 10 * 40 like so
import UIKit
class DynamicEmbeddedViewController : UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet weak var tableViewConstraint: NSLayoutConstraint!
@IBOutlet weak var tableView: UITableView!
let data = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Last"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TableViewCell")
//resize our constraint
let count = data.count
let constant = count * 40
tableViewConstraint.constant = CGFloat(constant)
self.updateViewConstraints()
//in a real app a delegate call back would be good to update the constraint on the scrollview
}
And in the first controller it would look like this.
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var containerViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
var dynamicView : DynamicEmbeddedViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if dynamicView != nil{
dynamicView?.tableView.reloadData()
//get size
let size = dynamicView?.tableView.contentSize.height
//cheating on the 300 because i see you set the other views in that controller at 150 each
containerViewHeightConstraint.constant = size! + 300
self.view.updateConstraintsIfNeeded()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ContainerViewSegue") {
dynamicView = segue.destination as? DynamicEmbeddedViewController
}
}
}
You can see we resize everything to fit. Other than that you got it right. Now to production worthy code. Most times you would know what content would be shown so you can control it. Another way is to use UITableView or UICollectionView for all the content and have different cells that would load based on the content. I hope this post clears it up a bit. I am sure we could continue to add to it but hopefully the concepts covered will be enough. If this answers your questions please show some love for the time it takes to do this. I can also upload this to GitHub if you like but it might be best to go in the repo you started.
這篇關于iOS:使用 ContainerView 動態內容的 UIScrollView(一步一步)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!