ios 将动态高度设置为 UIScrollView Swift

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40944994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:53:25  来源:igfitidea点击:

Setting Dynamic Height to UIScrollView Swift

iosuiscrollviewswift2height

提问by Jayesh Gyanchandani

how can i set the dynamic height of UIScrollViewbased on the content/ subviews i have in my ScrollView

如何根据ScrollView 中的内容/子视图设置UIScrollView的动态高度

Here is what i am getting as output:

这是我得到的输出:

enter image description here

在此处输入图片说明

回答by Patrick R

We can use auto layout, where we use a content view in scrollview, which can be pinned to the scrollview and the height and width constraints given equal to the main view. Then if we want the height to vary dynamically we can give height constraint a low priority compared to the others and hence the content view's height will increase based on its intrinsic size, because of its sub views.

我们可以使用自动布局,我们在滚动视图中使用内容视图,它可以固定到滚动视图,并且高度和宽度约束等于主视图。然后,如果我们希望高度动态变化,我们可以给高度约束一个比其他人低的优先级,因此内容视图的高度将根据其固有大小增加,因为它的子视图。

Reference Links:

参考链接:

1) https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithScrollViews.html#//apple_ref/doc/uid/TP40010853-CH24-SW1

1) https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithScrollViews.html#//apple_ref/doc/uid/TP40010853-CH24-SW1

2) https://www.youtube.com/watch?v=6J22gHORk2I

2) https://www.youtube.com/watch?v=6J22gHORk2I

回答by vaibhav sharma

First you need set a subview height constraint of 0, then calculate data height (which you want to set in subview), and simply assign subview.heightConstraint.constant = data.height, then you need to set scrollView.contentsizewhich is based on subview height:

首先你需要设置一个子视图高度约束0,然后计算数据高度(你想在子视图中设置),然后简单地赋值subview.heightConstraint.constant = data.height,然后你需要设置scrollView.contentsize基于子视图高度的高度:

self.scrollView.contentSize = CGSize(width: self.scrollView.contentSize.width, height: self.subViewHeight.constant)

回答by Hattori Hanzō

for me this this trick worked (Swift 4)

对我来说,这个技巧有效(Swift 4)

scrollView.layoutIfNeeded()
scrollView.isScrollEnabled = true
scrollView.contentSize = CGSize(width: self.view.frame.width, height: scrollView.frame.size.height)

回答by Vincent

You have to calculate the needed height for your content including spacing. Assign that value as the height of the row and refresh the table (or part in it with the row)

您必须计算内容所需的高度,包括间距。将该值指定为行的高度并刷新表格(或与行一起刷新表格)