如何解决使用 SwiftUI 的 PageTabViewStyle TabView 页面滑动不流畅
使用 Swift5.3.2、iOS14.4.2、XCode12.4,
我正在尝试在 SwiftUI 中创建一个 PageView,使用 iOS14 的新 PageTabViewStyle
for TabViews。
只要我不以任何方式对 onChange
进行任何类型的 selectedindex
操作,一切都有效。
一旦我执行 .onChange(of: selectedindex) { newidx in ...}
,滑动就会滞后并且不再能接受可用性。
但我的应用需要跟踪页面索引,并且需要在任何索引更改时执行代码。
如何在 SwiftUI 的 PageView 中检测滑动动作??
我意识到,一旦我将任何类型的 .onReceive()
或 .onChange(of: )
与 selectedindex
或其任何发布者一起使用,我总是以不再平滑的滑动手势结束.
我怎样才能克服这个问题并获得平滑的滑动和索引信息?
这是我的代码:
struct CustomPageView: View {
@Observedobject var myPageSelectionService = PageSelectionService()
@State private var contents = ["a","b","c"]
@State private var selectedindex: Int = 0
var body: some View {
TabView(selection: $selectedindex) {
ForEach(0..<contents.count,id:\.self) { i in
Text(contents[i]).tag(i)
}
}
.tabViewStyle(PageTabViewStyle(indexdisplayMode: .automatic))
.onChange(of: selectedindex) { newIndex in
print(newIndex)
}
}
}
我还尝试了发布者方法,将 selectedindex
替换为 myService.selectedindex。但没有变化 - 当滑动和内存超过循环时应用程序停止!
class MyService: ObservableObject {
@Published var selectedindex = 0
}
有什么可做的?
如果好奇,这里是整个应用程序:
import SwiftUI
enum MyState {
case waiting
case running
}
class AppState: ObservableObject {
@Published var myState: MyState = .running
}
class MyService: ObservableObject {
@Published var someServiceValue = 0
}
struct MainView: View {
@StateObject var appState = AppState()
@StateObject var myService = MyService()
var body: some View {
ParentView()
.environmentObject(appState)
.environmentObject(myService)
}
}
struct ParentView: View {
@EnvironmentObject var appState: AppState
@EnvironmentObject var myService: MyService
var body: some View {
NavigationView {
ZStack {
switch appState.myState {
case .waiting:
Text("Waiting")
case .running:
ChildView()
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
.onChange(of: myService.someServiceValue) { newValue in
if newValue == 4 {
appState.myState = .waiting
}
}
}
}
struct ChildView: View {
@EnvironmentObject var myService: MyService
@State private var contents = ["img_team_ivo","img_team_beat","img_team_benny","img_team_irfan","img_team_jenny","img_team_lukas","img_team_sabrina","img_team_nici","img_team_pascal","img_team_patrick","img_team_silvan","img_team_stephan","img_team_christoph"]
@State private var selectedindex: Int = 0
var body: some View {
ZStack {
ScrollView {
ZStack {
TabView(selection: $selectedindex) {
ForEach(0..<contents.count,id:\.self) { index in
ZStack {
Image(contents[index])
.resizable()
.scaledToFit()
}
}
}
.tabViewStyle(PageTabViewStyle(indexdisplayMode: .automatic))
}
}
}
.onChange(of: selectedindex) { newIdx in
// !!!!!!!!!! app stalls - no more smooth swiping of Pages :(
myService.someServiceValue = newIdx
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。