In a SwiftUI application I am working with, I have a TabView that I use with paginated style. Each Page of the TabView is a full screen item and each every one of those pages have some action button placed on navigation bar on top (top trailing).
The problem I am facing this is, when I keep on swiping between the pages, the navigation button multiplies for split second as it is displaying the next or previous page’s toolbar buttons together. After half a second or so it only shows the current page’s button only.
Attached below is screen recording of the problem and the sample code to demonstrate.
https://ibb.co/kBQ30n0 (sorry I can’t upload gif file to SO as it gives error)
import SwiftUI
struct Model: Identifiable {
internal init(id: UUID = .init(), position: Int) {
self.id = id
self.position = position
self.color = .red
}
let id: UUID
var position: Int
var color: Color
var title: String { return "item: (position)" }
var shortTitle: String { return "(position)" }
}
struct ContentView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
NavigationStack {
TabView {
ForEach(viewModel.models) { model in
Modelview(model: model)
}
}
.tabViewStyle(.page(indexDisplayMode: .always))
.navigationTitle("Title")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct Modelview: View {
var model: Model
var body: some View {
Rectangle().fill(model.color)
.overlay(alignment: .center) {
Text(model.title).font(.title).foregroundStyle(.black)
.padding().background(in: .rect, fillStyle: .init())
}
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button(action: {}, label: { Text(model.shortTitle) })
}
}
}
}
class ViewModel: ObservableObject {
@Published var models: [Model] = []
init() {
let count = 30
var items: [Model] = []
for i in 0..<count {
items.append(.init(position: i+1))
}
self.models = items
}
}
#Preview {
ContentView()
}
If anyone has encountered a similar problem and found a better way to handle the situation, I really appreciate any helpful tips.
In summary, what needs to happen is, for a similar full page swipe between events, the navigation bar buttons need to be customised based on current page’s content. The demonstrated code is for a very simple use case, but totally reproducible.
Thanks