WWDC24 deal: 30% off our Swift and SwiftUI books! Learn more ...WWDC24 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

Creating gradient on polylines in SwiftUI MapKit

When using MapKit and SwiftUI, Xcode will autocomplete to suggest you use linearGradient(_:startPoint:endPoint:options:) to style a MapPolyline. The linearGradient() method requires you to provide a start and end point in the screen space. However, most of the time, if you are reaching for a gradient, you want it to follow the line along the map.

By passing a Gradient directly to the stroke() modifier, you can avoid needing to provide a screen space startPoint and endPoint, allowing the gradient to follow the line on the map.

MapPolyline(
    coordinates: coordinates
)
.stroke(
    Gradient(colors: [.red, .indigo])
)

This approach simplifies the implementation and creates a more visually appealing effect.

Books by Natalia PanferovaBooks by Natalia Panferova
WWDC24: 30% off all books!
  • Swift Gems

    100+ tips to take your Swift code to the next level

  • Integrating SwiftUI into UIKit Apps

    A detailed guide on gradually adopting SwiftUI in UIKit projects

The offer is active until the 16th of June.