Skip to content

Instantly share code, notes, and snippets.

@maximkrouk
Last active September 17, 2020 22:05
Show Gist options
  • Save maximkrouk/eafe497279067df303d30372c5ba0f29 to your computer and use it in GitHub Desktop.
Save maximkrouk/eafe497279067df303d30372c5ba0f29 to your computer and use it in GitHub Desktop.
Custom SwiftUI foreground
import SwiftUI
// MARK: - API
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension View {
public func foreground<Overlay: View>(_ overlay: Overlay) -> some View {
_Foreground(overlay: overlay, for: self)
}
}
// MARK: - Implementation
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
private struct _Foreground<Content: View, Overlay: View>: View {
let content: Content
let overlay: Overlay
internal init(overlay: Overlay, for content: Content) {
self.content = content
self.overlay = overlay
}
var body: some View {
content.overlay(overlay).mask(content)
}
}
// I think, that `Foreground.swift` approach is better, but there is an alternative without custom view.
import SwiftUI
// MARK: - API
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension View {
public func foreground<Overlay: View>(_ overlay: Overlay) -> some View {
self.overlay(overlay).mask(self)
}
}
@maximkrouk
Copy link
Author

maximkrouk commented Mar 7, 2020

Usage example

HStack {
    Text("Burned")
    Image(systemName: "flame")
}.foreground(LinearGradient(...))

My answer on stackoverflow

Back to index

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment