gpt4 book ai didi

SwiftUI : How to implement SwipGesture?

转载 作者:行者123 更新时间:2023-11-30 10:32:19 25 4
gpt4 key购买 nike

我想创建一个 UISwipeGestureRecognizer 以便能够在 UIViewRepresentable 中导航。

基本上,用户到达主页后可以向左或向右滑动并将其带到相关 View 。

此外,我只是想注意到我已经做了很多研究,但我没有在 SwiftUI 中看到任何关于 SwipeGesture 的内容(Apple 文档非常简短,没有显示示例)

这是我目前的代码:

struct SheetMenu: View {

@State var currentPage = 0

var body: some View {
GeometryReader { geo in
ZStack {
if self.currentPage == 0 {
Text("Page 1")
}
else if self.currentPage == 1 {
Text("Page 2")
}

else if self.currentPage == 2 {
Text("Page 3")
}

else if self.currentPage == 3 {
Text("Page 4")
}

else if self.currentPage == 4 {
Text("Page 5")
}

else if self.currentPage == 5 {
Text("Page 6")
}

else if self.currentPage == 6 {
Text("Page 7")
}
}
.backGroundColor(colorBackGround)
PageControl(current: self.currentPage)
.position(x: geo.size.width/2, y: geo.size.height)
}
}
}

struct PageControl : UIViewRepresentable {

var current = 0

func makeUIView(context: UIViewRepresentableContext<PageControl>) -> UIPageControl {
let page = UIPageControl()
page.numberOfPages = 7
page.currentPageIndicatorTintColor = .black
page.pageIndicatorTintColor = .gray
return page
}

func updateUIView(_ uiView: UIPageControl, context: UIViewRepresentableContext<PageControl>) {
uiView.currentPage = current
}
}

最佳答案

手势是 View 上的修饰符。您可以通过拖动来假装滑动(您可能需要为手势添加超时)。请注意,我必须扩展您的文本框架,否则手势仅在您位于文本顶部时才能识别:

struct ContentView: View {

@State var currentPage = 0

var body: some View {
GeometryReader { geo in
PageControl(current: self.currentPage)
.position(x: geo.size.width/2, y: geo.size.height)
Text("Page: \(self.currentPage)")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.gesture(
DragGesture()
.onEnded {
if $0.translation.width < -100 {
self.currentPage = max(0, self.currentPage - 1)
} else if $0.translation.width > 100 {
self.currentPage = min(6, self.currentPage + 1)
}
}
)
}
}
}

struct PageControl : UIViewRepresentable {

var current = 0

func makeUIView(context: UIViewRepresentableContext<PageControl>) -> UIPageControl {
let page = UIPageControl()
page.numberOfPages = 7
page.currentPageIndicatorTintColor = .black
page.pageIndicatorTintColor = .gray
return page
}

func updateUIView(_ uiView: UIPageControl, context: UIViewRepresentableContext<PageControl>) {
uiView.currentPage = current
}
}

关于SwiftUI : How to implement SwipGesture?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58891309/

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