gpt4 book ai didi

ios - SwiftUI:仅当 ScrollView 超过屏幕高度时才可滚动

转载 作者:行者123 更新时间:2023-12-01 18:03:31 69 4
gpt4 key购买 nike

目前我有一个看起来像这样的 View 。

struct StatsView: View {
var body: some View {
ScrollView {
Text("Test1")
Text("Test2")
Text("Test3")
}
}
}

这会在 ScrollView 中呈现一个包含 3 个文本的 View ,每当我在屏幕中拖动这些文本中的任何一个时, View 都会移动导致其可滚动,即使这 3 个文本适合屏幕并且还有剩余空间。我想要实现的是仅在其内容超过屏幕高度大小时才使 ScrollView 可滚动,如果不是,我希望 View 是静态的并且不要移动。我尝试使用 GeometryReader 并将 ScrollView 框架设置为屏幕宽度和高度,内容也相同,但我仍然有相同的行为,我也尝试过设置 minHeight、maxHeight 没有任何运气。

我怎样才能做到这一点?

最佳答案

出于某种原因,我无法完成上述任何一项工作,但它确实激励我找到了适合我的解决方案。它不像其他的那样灵活,但可以很容易地适应支持两个滚动轴。

import SwiftUI

struct OverflowContentViewModifier: ViewModifier {
@State private var contentOverflow: Bool = false

func body(content: Content) -> some View {
GeometryReader { geometry in
content
.background(
GeometryReader { contentGeometry in
Color.clear.onAppear {
contentOverflow = contentGeometry.size.height > geometry.size.height
}
}
)
.wrappedInScrollView(when: contentOverflow)
}
}
}

extension View {
@ViewBuilder
func wrappedInScrollView(when condition: Bool) -> some View {
if condition {
ScrollView {
self
}
} else {
self
}
}
}

extension View {
func scrollOnOverflow() -> some View {
modifier(OverflowContentViewModifier())
}
}
用法
VStack {
// Your content
}
.scrollOnOverflow()

关于ios - SwiftUI:仅当 ScrollView 超过屏幕高度时才可滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62463142/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com