简体   繁体   English

根据内容动画 UIScrollView 的高度

[英]Animate the height of a UIScrollView based on it's content

My situation:我的情况:

I have a horizontal ScrollView containing a StackView.我有一个包含 StackView 的水平 ScrollView。 Inside this StackView there are some Views, that can be expanded/collapsed.在这个 StackView 中有一些可以展开/折叠的视图。

When I want to expand one of these Views, I first unhide some subViews in the View.当我想扩展这些视图之一时,我首先取消隐藏视图中的一些子视图。 After that I need to change the height of the ScrollView based on the new height of this View.之后,我需要根据此视图的新高度更改 ScrollView 的高度。

But this is not working...但这不起作用......

I try this code:我试试这个代码:

        UIView.animate(withDuration: 0.3) { [self] in
            // Toggle hight of all subViews
            stackView.arrangedSubviews.forEach { itemView in
                guard let itemView = itemView as? MyView else { return }
                itemView.toggleView()
            }
            
            // Now update the hight of the StackView
            // But here the hight is always from the previous toggle
            let height = self.stackView.arrangedSubviews.map {$0.frame.size.height}.max() ?? 0.0
            print(height)

            heightConstraint.constant = height
        }

This code nicely animates, but always to the wrong height.这段代码很好地动画,但总是错误的高度。 So the ScrollView animates to collapsed when it should be expanded and expanded when it should be collapsed.所以 ScrollView 在应该展开时动画折叠,在应该折叠时展开。

Anyone with on idea how to solve this?有人知道如何解决这个问题吗?

The problem is that, whatever you are doing here:问题是,无论你在这里做什么:

itemView.toggleView()

may have done something to change the height a view, but then you immediately call:可能已经做了一些改变视图高度的事情,但是你立即调用:

let height = self.stackView.arrangedSubviews.map {$0.frame.size.height}.max() ?? 0.0

before UIKit has updated the frames.UIKit 更新框架之前。

So, you can either track your own height property, or...因此,您可以跟踪自己的高度属性,或者...

get the frame heights after the update - such as with:在更新获取框架高度 - 例如:

    DispatchQueue.main.async {
        let height = self.stackView.arrangedSubviews.map {$0.frame.size.height}.max() ?? 0.0
        print("h", height)
        self.scrollHeightConstraint.constant = height
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM