【问题标题】:Animate the height of a UIScrollView based on it's content根据内容为 UIScrollView 的高度设置动画
【发布时间】:2021-09-12 17:48:49
【问题描述】:

我的情况:

我有一个包含 StackView 的水平 ScrollView。 在这个 StackView 里面有一些 Views,可以展开/折叠。

当我想展开其中一个 View 时,我首先取消隐藏 View 中的一些 subView。之后我需要根据这个 View 的新高度来改变 ScrollView 的高度。

但这不起作用...

我试试这个代码:

        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
        }

这段代码的动画效果很好,但总是高度错误。 所以 ScrollView 动画在它应该展开时折叠,当它应该折叠时展开。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 你能添加一些图形或演示吗?

标签: ios swift uiscrollview uistackview


【解决方案1】:

问题是,无论你在这里做什么:

itemView.toggleView()

可能已经做了一些事情来改变视图的高度,但是你立即调用:

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

之前 UIKit 更新了框架。

因此,您可以跟踪 自己的 height 属性,或者...

获取更新后的帧高度 - 例如:

    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()
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2013-11-22
    相关资源
    最近更新 更多