Home > Software design >  Kingfisher Image takes full width
Kingfisher Image takes full width

Time:08-24

I am loading images from URLs with the KFImage of the Kingfisher Library. There is the probability that some URLs are invalid. So Kingfisher will not be able to load an image from this url. In this case i would like to collapse the KFImage.

HStack(alignment: .top) {
    KFImage(someUrl)
    Text("some Text")
}

In this case the KFImage takes all place it can take. I found a solution with the onSuccess Listener of KFImage.

KFImage(url)
    .onSuccess { _ in
       self.canLoadImage = true
    }
    .forceRefresh()
    .resizable()
    .aspectRatio(contentMode: .fill)
    .cornerRadius(20)
    .clipped()
    .frame(width: canLoadImage ? 150 : 0)
}

In this case the Image collapses and on Failure but has a width on Success. But this solution seems too complex to be the best solution possible. Since i am quiet new iOS development my ideas for better solutions are quiet limited.

CodePudding user response:

You can completely remove the image from the View using an if statement:

if canLoadImage {
    KFImage(url)
        .onSuccess { _ in
            self.canLoadImage = true
        }
        .forceRefresh()
        .resizable()
        .aspectRatio(contentMode: .fill)
        .cornerRadius(20)
        .clipped()
        .frame(width: 150)
}

CodePudding user response:

Not really clear what do you want, but if you want to remove it on failure completely (instead of decrease some size) just make it conditional, like

@State private var imageVisible = true

...

HStack(alignment: .top) {
    if imageVisible {
      KFImage(someUrl)
        .onFailure { _ in
            imageVisible = false
        }
    }
    Text("some Text")
}
  • Related