英文:
swift ui left edge swipe gesture navigate back to previous view not working
问题
你好,我有一个简单的消息应用程序,我正在尝试实现从左边缘向右滑动的手势,以便从ChatView导航回MessagesHomeView。我遇到的问题是在滚动视图上捕捉这些手势。由于聊天视图除了顶部标题栏之外都是一个大的滚动视图,我还必须从滚动视图中检测到边缘滑动。当我将.gesture块添加到整个视图时,只有顶部标题栏上的拖动手势被捕捉到,并且代码被正确执行。但是,无法从滚动视图部分检测到边缘拖动。因此,我尝试将.gesture块添加到滚动视图,但是当我这样做时,屏幕会冻结,应用程序停止工作。我希望能够获得在滚动视图外检测这些边缘拖动的任何帮助。
import SwiftUI
struct ChatView: View {
@State private var offset = CGSize.zero
var body: some View {
VStack {
VStack{
Text("header")
}.frame(height: 80)
ScrollView {
LazyVStack{
}
}.gesture (
DragGesture()
.onChanged { gesture in
if gesture.startLocation.x < CGFloat(40.0){
if gesture.translation.width > 0 {
offset = gesture.translation
if offset.width > 200.0 {
leaveView()
}
}
}
}.onEnded { _ in
withAnimation{
offset = CGSize.zero
}
}
)
}
.offset(x: offset.width)
}
}
英文:
Hello I have a simple messaging app and I am trying to implement a left edge swipe gesture to the right in order to navigate out of the ChatView and back to the MessagesHomeView. The problem I'm running into is picking up these gestures over the scroll view. Since the chat view is one big scroll view except for a top header I have to detect edge swipes from the scroll view as well. When I add the .gesture block to the overall view, only drags on the top header are picked up and the code is executed correctly. But edge drags are not detected from the scroll view portion. Therefor I tried adding the .gesture block to the scroll view but when I try this the screen freezes and the app stops working. I would appreciate any help in detecting these edge drags off the scroll view.
import SwiftUI
struct ChatView: View {
@State private var offset = CGSize.zero
var body: some View {
VStack {
VStack{
Text("header")
}.frame(height: 80)
ScrollView {
LazyVStack{
}
}.gesture (
DragGesture()
.onChanged { gesture in
if gesture.startLocation.x < CGFloat(40.0){
if gesture.translation.width > 0 {
offset = gesture.translation
if offset.width > 200.0 {
leaveView()
}
}
}
}.onEnded { _ in
withAnimation{
offset = CGSize.zero
}
}
)
}
.offset(x: offset.width)
}
}
答案1
得分: 0
这是如何使用 NavigationStack 在 MessagesHomeView 中向后滑动到 MessagesHomeView 的代码示例:
struct MessagesHomeView: View {
var body: some View {
NavigationStack {
VStack {
Spacer()
NavigationLink(destination: ChatView()) {
Text("导航到聊天")
}
Spacer()
}
}
}
}
struct ChatView: View {
var body: some View {
VStack {
VStack{
Text("聊天")
}
.frame(height: 80)
ScrollView {
LazyVStack{
}
}
}
}
}
请注意,这只是一个代码示例,具体的实现可能需要根据你的项目需求进行调整。
英文:
This is how you can swipe back to your MessagesHomeView with a NavigationStack
struct MessagesHomeView: View {
var body: some View {
NavigationStack {
VStack {
Spacer()
NavigationLink(destination: ChatView()) {
Text("Navigate to Chat")
}
Spacer()
}
}
}
}
struct ChatView: View {
var body: some View {
VStack {
VStack{
Text("Chats")
}
.frame(height: 80)
ScrollView {
LazyVStack{
}
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论