如何动态增加滚动视图的高度? [英] how to dynamically increase the height of scroll view?

查看:30
本文介绍了如何动态增加滚动视图的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在滚动视图中放置了一个表格视图和一个视图,如何根据表格视图中的单元格数量和内容视图中的内容动态更改滚动视图的高度

i placed a table view and a view in a scroll view how to change the scroll view's height dynamically depending on the number of cells in the table view and the content present in content view also

推荐答案

您需要设置 ScrollView 的 contensize.您可以通过适当的自动布局或以编程方式进行

You need to set contensize of your ScrollView. You can do it by proper autolayout or programatically as

CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;

Swift 3

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var contentRect = CGRect.zero
     for view: UIView in scrollView.subviews {
        contentRect = contentRect.union(view.frame)  
     }
contentRect.size.height = contentRect.size.height + 20
scrollView.contentSize = contentRect.size
}

Swift 4

这是 Swift 4 中更简洁的版本. Swift 4 归功于此

Here is a more concise version in Swift 4. Credit for Swift 4 to this ans

 extension UIScrollView {
    func updateContentView() {
         contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
     }
 }

您可以在故事板中完成相同的操作.有 hack 可以做到这一点.

You can accomplish the same in storyboard. There is hack to accomplish that.

  1. 根据要求向滚动视图的顶部、左侧、右侧和高度添加约束为 1000 或更多.您的滚动视图可能会超出您的视图控制器高度本身.

  1. Add Constraints to scrollview top, left , right and height as 1000 or more as per requirement. Your Scroll View may exceed your view controller height itself.

然后您可以在 Scroll View Bottom & 之间添加 Constrain最后一个子视图(在您的情况下 View 包含 TableView 和 PaymentView )底部为 0 或 10.

Then you can add Constrain between your Scroll View Bottom & Last Subview (in your case View containing TableView and PaymentView ) Bottom as 0 or with 10.

3.您现在可以删除您的高度限制.

3.You can now delete your height constraint.

但在此之前,请确保滚动视图的所有子视图之间的约束是正确的.

But before this make sure consraints between all subviews of scrollview is proper.

希望有帮助.快乐编码!!

Hope it helps. Happy Coding!!

这篇关于如何动态增加滚动视图的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆