MP

Creating a Background Gradient with SwiftUI

Creating a gradient background in SwiftUI follows a similar process to UIKit: create a set of colors, define a start and endpoint, create a view from that gradient, and then assign it as the background of another view. Thankfully, SwiftUI handles the view creation for you, so the resulting code ends up a lot neater.

For example, in UIKit:

let gradient = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = [UIColor.white.cgColor, UIColor.blue.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

let gradientView = UIView()
gradientView.layer.insertSublayer(gradient, at: 0)
view.backgroundView = gradientView

And in SwiftUI:

.background(StaticMember(
    LinearGradient(
        gradient: Gradient(colors: [Color.white, Color.blue]),
        startPoint: .topLeading,
        endPoint: .bottomTrailing
    )
))