Search code examples
iosswiftswiftuikingfisher

Kingfisher Image takes full width


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.


Solution

  • 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)
    }