Skip to content

Commit

Permalink
Fine-tune for the image rendering trigger
Browse files Browse the repository at this point in the history
Especially when startLoadingBeforeViewAppear is true
  • Loading branch information
onevcat committed Feb 22, 2023
1 parent 415b1d9 commit 2eb1cff
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
31 changes: 25 additions & 6 deletions Sources/SwiftUI/ImageBinder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,23 @@ extension KFImage {

// Do not use @Published due to https://github.com/onevcat/Kingfisher/issues/1717. Revert to @Published once
// we can drop iOS 12.
var loaded = false { willSet { objectWillChange.send() } }
private(set) var loaded = false

private(set) var animating = false

var loadedImage: KFCrossPlatformImage? = nil { willSet { objectWillChange.send() } }
var progress: Progress = .init() { willSet { objectWillChange.send() } }
var progress: Progress = .init()

func markLoading() {
loading = true
}

func markLoaded(sendChangeEvent: Bool) {
loaded = true
if sendChangeEvent {
objectWillChange.send()
}
}

func start<HoldingView: KFImageHoldingView>(context: Context<HoldingView>) {
guard let source = context.source else {
Expand All @@ -58,7 +72,7 @@ extension KFImage {
self.loadedImage = image
}
self.loading = false
self.loaded = true
self.markLoaded(sendChangeEvent: false)
}
return
}
Expand Down Expand Up @@ -87,12 +101,17 @@ extension KFImage {
case .success(let value):
CallbackQueue.mainCurrentOrAsync.execute {
if let fadeDuration = context.fadeTransitionDuration(cacheType: value.cacheType) {
self.animating = true
let animation = Animation.linear(duration: fadeDuration)
withAnimation(animation) { self.loaded = true }
withAnimation(animation) {
// Trigger the view render to apply the animation.
self.markLoaded(sendChangeEvent: true)
}
} else {
self.loaded = true
self.markLoaded(sendChangeEvent: false)
}
self.loadedImage = value.image
self.animating = false
}

CallbackQueue.mainAsync.execute {
Expand All @@ -103,7 +122,7 @@ extension KFImage {
if let image = context.options.onFailureImage {
self.loadedImage = image
}
self.loaded = true
self.markLoaded(sendChangeEvent: true)
}

CallbackQueue.mainAsync.execute {
Expand Down
3 changes: 2 additions & 1 deletion Sources/SwiftUI/KFImageRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ struct KFImageRenderer<HoldingView> : View where HoldingView: KFImageHoldingView
let context: KFImage.Context<HoldingView>

var body: some View {
if context.startLoadingBeforeViewAppear && !binder.loadingOrSucceeded {
if context.startLoadingBeforeViewAppear && !binder.loadingOrSucceeded && !binder.animating {
binder.markLoading()
DispatchQueue.main.async { binder.start(context: context) }
}

Expand Down

0 comments on commit 2eb1cff

Please sign in to comment.