Reputation: 2268
I am trying to load image from server in a slide show with SwiftUi
but image is not loading in the slide show. please see my code below
import SwiftUI
import Combine
struct ImageCarouselView<Content: View>: View {
private var numberOfImages: Int
private var content: Content
@State private var currentIndex: Int = 0
private let timer = Timer.publish(every: 3, on: .main, in: .common).autoconnect()
init(numberOfImages: Int, @ViewBuilder content: () -> Content) {
self.numberOfImages = numberOfImages
self.content = content()
}
var body: some View {
GeometryReader { geometry in
// 1
ZStack(alignment: .bottom) {
HStack(spacing: 0) {
self.content
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .leading)
.offset(x: CGFloat(self.currentIndex) * -geometry.size.width, y: 0)
.animation(.spring())
.onReceive(self.timer) { _ in
self.currentIndex = (self.currentIndex + 1) % (self.numberOfImages == 0 ? 1 : self.numberOfImages)
}
// 2
HStack(spacing: 3) {
// 3
ForEach(0..<self.numberOfImages, id: \.self) { index in
// 4
Circle()
.frame(width: index == self.currentIndex ? 10 : 8,
height: index == self.currentIndex ? 10 : 8)
.foregroundColor(index == self.currentIndex ? Color.blue : .white)
.overlay(Circle().stroke(Color.gray, lineWidth: 1))
.padding(.bottom, 8)
.animation(.spring())
}
}
}
}
}
}
and in my view
struct MainView: View {
@Binding var showMenu: Bool
@State var index = 0
var body: some View {
ScrollView {
//MainView(with:"https://govcard.net/banners/banner1.jpg")
GeometryReader { geometry in
ImageCarouselView(numberOfImages: 3) {
Image("image_carousel_1")
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
Image("image_carousel_2")
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
Image("image_carousel_3")
.resizable()
.scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
}.frame(height: 200, alignment: .center)
}
i want to use url instead of asset image.
Upvotes: 0
Views: 563
Reputation: 16341
As far as I've seen the easiest way would be to add the Kingfisher Swift package
to your project.import KingfisherSwiftUI
to your swift file and use the KFImage(myUrl)
.
import KingfisherSwiftUI
struct MainView: View {
//...
KFImage(URL(string: "https://example.com/image.png")!)
}
Here are the steps to add the Kingfisher
to your project:
Upvotes: 1