Interface: SwiftUI
Life Cycle: SwiftUI
Language: Swift
Xcode version: 12.5
I want to use a page indicator in the custom carousel view with core data. The indicator works fine with the current code below, but if a page is added or deleted from Core Data, the number of indicators does not change.
When adding or deleting a page, pages.count is changed, but I checked that func makeUIView() is not executed again.
How can I reload the func makeUIView automatic, when the value of self.pages.count changed?
struct PageControl : UIViewRepresentable {
@EnvironmentObject var ani: CarouselModel
@FetchRequest(entity: Page.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Page.name, ascending: true)]
) var pages: FetchedResults<Page>
func makeUIView(context: Context) -> UIPageControl {
let view = UIPageControl()
view.currentPageIndicatorTintColor = UIColor(red: 100/255, green: 255/255, blue: 177/255, alpha: 1.0)
view.pageIndicatorTintColor = UIColor(red: 100/255, green: 255/255, blue: 177/255, alpha: 1.0).withAlphaComponent(0.2)
view.numberOfPages = self.pages.count + 1
return view
}
func updateUIView(_ uiView: UIPageControl, context: Context) {
// Updating Page Indicator When Ever Page Changes...
DispatchQueue.main.async {
uiView.currentPage = Int(self.ani.count)
}
}
}
I got it!
Put the below line from func makeUIView to func updateUIView
uiView.numberOfPages = pages.count + 1
Final
func updateUIView(_ uiView: UIPageControl, context: Context) {
// Updating Page Indicator When Ever Page Changes...
DispatchQueue.main.async {
uiView.currentPage = Int(self.ani.count)
uiView.numberOfPages = pages.count + 1
}
}