tscheppe
tscheppe

Reputation: 698

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.

Upvotes: 2

Views: 2412

Answers (2)

Asperi
Asperi

Reputation: 257573

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

Upvotes: 2

RelativeJoe
RelativeJoe

Reputation: 5084

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

Upvotes: 3

Related Questions