After I custom Tab layout (without using TabView fore more custom style) and enable to switching menu for change view, I found some issue with content in View will reset.
Example video. After I click to second tab and back to the Home tab, ScrollView in HomeView will reset offset to top.
ContentView.swift
FYI: It's bad way that I move view instance into other class like ViewModel. I just try.
struct ContentView: View {
@StateObject private var vm = MainViewModel()
var body: some View {
VStack {
ZStack {
switch vm.currentIndexSelect {
case 1: vm.homeView
case 2: vm.chatView
default: EmptyView()
}
}.frame(maxWidth: .infinity, maxHeight: .infinity)
HStack {
Button {
vm.currentIndexSelect = 1
} label: {
Text("Home")
}
Button {
vm.currentIndexSelect = 2
} label: {
Text("Chat")
}
}
}
}
}
ViewModel
class MainViewModel: ObservableObject {
@Published var homeView = HomeView()
@Published var chatView = ChatView()
@Published var currentIndexSelect: Int = 1
}
HomeView.swift
struct HomeView: View, Equatable {
var body: some View {
ScrollView {
ForEach(1..<20) { index in
RoundedRectangle(cornerRadius: 12)
.foregroundColor(.red)
.frame(width: 200)
.aspectRatio(1, contentMode: .fit)
.overlay {
Text("\(index)")
}
}
}
}
}
At the first time, I thought it was a problem with State it will re-render view inside ( re-initiate ). So I move will into view model ( Bad Idea ) instead for save instance of Views but It still doesn't work.
Has anyone ever face this problem ?
1. Use TabView
with page style
TabView(selection: $currentIndexSelect) {
HomeView().tag(1)
ChatView().tag(2)
}
.onAppear {
UIScrollView.appearance().isScrollEnabled = false
}
.tabViewStyle(.page(indexDisplayMode: .never))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.