Skip to content

Instantly share code, notes, and snippets.

@avii-7
Created December 12, 2024 18:10
Show Gist options
  • Select an option

  • Save avii-7/9d8edb2632907ffa167a3a8e66d50637 to your computer and use it in GitHub Desktop.

Select an option

Save avii-7/9d8edb2632907ffa167a3a8e66d50637 to your computer and use it in GitHub Desktop.
Shimmer Animation
import Foundation
import SwiftUI
extension View {
@ViewBuilder
func shimmer(when isLoading: Bool) -> some View {
if isLoading {
self.modifier(Shimmer())
.redacted(reason: .placeholder)
}
else {
self
}
}
}
public struct Shimmer: ViewModifier {
@State private var startAnimation = false
public func body(content: Content) -> some View {
content
.mask {
LinearGradient(
colors: [.black.opacity(0.4), .black, .black.opacity(0.4)],
startPoint: startAnimation ? .init(x: 1, y: 1) : .init(x: -0.3, y: -0.3),
endPoint: startAnimation ? .init(x: 1.3, y: 1.3) : .init(x: 0, y: 0)
)
}
.animation(.linear(duration: 2).delay(0.24).repeatForever(autoreverses: false), value: startAnimation)
.onAppear {
startAnimation.toggle()
}
}
}
// Sample
import SwiftUI
struct List_Shimmer: View {
@State private var fruits: [Fruit] = Fruit.placeholder
@State private var isLoading = true
var body: some View {
VStack {
List(fruits, id: \.self) { item in
HStack {
Image(systemName: item.systemImage)
.font(.title2)
VStack (alignment: .leading) {
Text(item.title)
.font(.headline)
Text(item.description)
.font(.subheadline)
}
}
.shimmer(when: isLoading)
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
isLoading = false
fruits = [
Fruit(name: "apple", title: "Apple", description: "A sweet red fruit", systemImage: "applelogo")
]
}
}
}
}
#Preview {
List_Shimmer()
}
struct Fruit: Hashable {
let name: String
let title: String
let description: String
let systemImage: String
}
extension Fruit {
static var placeholder: [Fruit] {
return [
Fruit(name: "apple", title: "Apple", description: "A sweet red fruit", systemImage: "applelogo"),
Fruit(name: "banana", title: "Banana", description: "A long yellow fruit", systemImage: "leaf"),
Fruit(name: "cherry", title: "Cherry", description: "A small red fruit", systemImage: "drop"),
Fruit(name: "grape", title: "Grape", description: "A cluster of small purple fruits", systemImage: "circle"),
Fruit(name: "orange", title: "Orange", description: "A round citrus fruit", systemImage: "sun.max"),
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment