Setting Dynamic Height to UIScrollView Swift

巧了我就是萌 提交于 2019-12-09 16:06:27

问题


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

Here is what i am getting as output:


回答1:


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

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




回答2:


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.contentsize which is based on subview height:

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



回答3:


for me this this trick worked (Swift 4)

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



回答4:


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)



来源:https://stackoverflow.com/questions/40944994/setting-dynamic-height-to-uiscrollview-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!