msdano
msdano

Reputation: 1

SwiftUI: Display an image based on the day of the year

I have 58 images in an asset folder on SwiftUI. I am interested in displaying image 1 for the entirety of the first day of the year, image 2 for the entirety of the second day of the year, image 3 for the entirety of the third day of the year, etc. until all 58 images have been displayed once each for the first 58 days of the year.

Once all of the images have had their day, I would like the process to start back over with image 1 on the 59th day of the year. I want this cyclical process to repeat until all 365 days of the year are completed. Is this possible? How can I get started?

This is what I am going for:

import SwiftUI

struct ContentView: View { var body: some View {

//if date = 1, then:   

    Image("Image 1")
    .resizable()
    .scaledToFit()

}

That process would continue for each date in the series.

Upvotes: 0

Views: 373

Answers (1)

Vadzim
Vadzim

Reputation: 71

Try to name each image in resource folder by day number. For example, name the first image “1,” the second “2” and etc. And use this code for fetching images.

import SwiftUI
import Foundation

struct ContentView: View { 
    var body: some View {
        Image(getImageName())
            .resizable()
            .scaledToFit()
    }

    private func getImageName() -> String {
        let day = Calendar.current.ordinality(of: .day, in: .year, for: Date())!
        let imagesCount = 58
        let imageName = day % imagesCount == 0 ? 1 : day % imagesCount
        return String(imageName)
    }
}

Upvotes: 1

Related Questions