Shimmer Effect In SwiftUI

Mobile Apps Academy
2 min readFeb 19, 2024

--

In this article, We will explore how to implement a Shimmer Effect in SwiftUI

Before proceeding, please consider subscribing to our YOUTUBE CHANNEL

It gives us a lot of motivation to produce high-quality content for you guys.

if you are interested in watching the video tutorial, Check out below.

Let's start by creating the required script ShimmerView

import SwiftUI

struct ShimmerView: View {

var body: some View {

}
}

We need 3 variables, startPoint, endPoint, and gradientColors.

We use a starting point and an end point to animate the direction of the shimmer.

import SwiftUI

struct ShimmerView: View {

@State private var startPoint: UnitPoint = .init(x: -1.8, y: -1.2)
@State private var endPoint: UnitPoint = .init(x: 0, y: -0.2)

private var gradientColors = [Color.gray.opacity(0.2), Color.white.opacity(0.2), Color.gray.opacity(0.2)]

var body: some View {

}
}

I have added a LinearGradient view with startPoint and endPoint which will be changing inside onAppear

import SwiftUI

struct ShimmerView: View {

@State private var startPoint: UnitPoint = .init(x: -1.8, y: -1.2)
@State private var endPoint: UnitPoint = .init(x: 0, y: -0.2)

private var gradientColors = [Color.gray.opacity(0.2), Color.white.opacity(0.2), Color.gray.opacity(0.2)]

var body: some View {
LinearGradient(colors: gradientColors, startPoint: startPoint, endPoint: endPoint)
.onAppear {
withAnimation(.easeInOut(duration: 1).repeatForever(autoreverses: false)) {
startPoint = .init(x: 1, y: 1)
endPoint = .init(x: 2.2, y: 2.2)
}
}
}
}

Using this ShimmerView, We can now create a dummy UI like below.

import SwiftUI

struct ShimmerEffectExample: View {
var body: some View {
VStack {
ShimmerEffect()
ShimmerEffect()
ShimmerEffect()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.ignoresSafeArea()
.background(.black)
}

@ViewBuilder
private func ShimmerEffect() -> some View {
VStack {
HStack {
ShimmerView()
.cornerRadius(30)
.frame(width: 60, height: 60)

VStack {
ShimmerView()
.cornerRadius(5)
.frame(height: 20)
ShimmerView()
.cornerRadius(5)
.frame(height: 20)
}
}
ShimmerView()
.cornerRadius(5)
.frame(height: 150)
}
}
}

Thats it. Below is the result.

Once again Thanks for stopping by.
Do check out our YOUTUBE CHANNEL

Social Handles

Instagram : https://www.instagram.com/mobileappsacademy/

Twitter : https://twitter.com/MobileAppsAcdmy

LinkedIn : https://www.linkedin.com/company/mobile-apps-academy/

--

--

Mobile Apps Academy

Welcome to Mobile Apps Academy, your go-to channel for all things mobile app development!