swift - UIScrollView 在缺口手机中给出了意想不到的结果
问题描述
我正在尝试在 SwiftUI 中构建可滚动的卡片。我已经使用 UIScrollView 使用 UIViewRepresentable 来实现一些附加功能(速度)。我想实现向下滑动以关闭卡片。我想出了以下代码,并使用了与 UIScrollView 提供的速度相同的交互式弹簧动画。问题是我的代码和动画在没有缺口的手机上运行良好,但在使用缺口手机时,我在动画中遇到了一些故障。
这是我的 UIScrollView 包装器
struct MyScrollView<Content: View>: UIViewRepresentable {
@ObservedObject var viewModel: ScrollViewModel
@ViewBuilder var content: () -> Content
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIScrollViewDelegate {
var parent: MyScrollView
var hostingController: UIHostingController<Content>!
init(_ parent: MyScrollView) {
self.parent = parent
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
self.parent.viewModel.velocity = velocity.y
}
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator
scrollView.isScrollEnabled = true
let child = UIHostingController(rootView: content())
child.view.backgroundColor = .clear
context.coordinator.hostingController = child
scrollView.addSubview(child.view)
let newSize = child.view.sizeThatFits(CGSize(width: UIScreen.Width, height: UIScreen.Height))
child.view.frame = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
scrollView.contentSize = newSize
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
context.coordinator.hostingController?.rootView = content()
}
typealias UIViewType = UIScrollView
}
这是我的数据
class ScrollViewModel: ObservableObject {
@Published var enable = true
@Published var velocity = CGFloat.zero
}
这是我的 ContentView
struct ContentView: View {
@StateObject var viewModel = ScrollViewModel()
var body: some View {
ZStack {
Button {
withAnimation(.interpolatingSpring(mass: 0.01, stiffness: 1, damping: 1, initialVelocity: -viewModel.velocity)) {
viewModel.enable = true
}
} label: {
Text("Enable")
.padding()
}
if viewModel.enable {
MyScrollView(viewModel: viewModel) {
RoundedRectangle(cornerRadius: 10)
.fill(.purple)
.frame(height: UIScreen.Height)
.offset(y: 50)
}
.onChange(of: viewModel.velocity) { newValue in
if viewModel.velocity < -2 {
withAnimation(.interpolatingSpring(mass: 0.01, stiffness: 1, damping: 1, initialVelocity: -viewModel.velocity)) {
viewModel.enable = false
}
}
}
.transition(.move(edge: .bottom))
}
}
}
}
我不知道是什么导致了这个问题。我需要一些帮助。提前致谢 !
解决方案
推荐阅读
- mql4 - 为什么在 MQL4 中值更改时显示标签编号不更改?
- cloud - IBM Cloud 未创建 Lite Plan 实例
- sql - REGEXP CONTAINS 来自拆分的字符串
- mongodb - 通过亚马逊网络服务自动化 mongo db 备份
- c# - 将本地 JSON 文件中的内容加载到包含 AngularJS 的 MVC 项目中
- javascript - 如何将数据从 AntD 表传递到 React 中的另一个组件?
- pandas - Python panda 多索引数据框:如何将特定列与新索引中的特定值相关联
- google-cloud-platform - PythonVirtualenvOperator 因 TypeError 失败:无法腌制“模块”对象
- php - 带有 WP_Query 的页面上的 ACF Pro 块上的 Wordpress 分页
- c# - 用于 mysql .net5 的 Nuget 包