Gradient as foreground color of Text in SwiftUI

后端 未结 6 1059
终归单人心
终归单人心 2021-02-08 12:55

Is there any way of using a gradient as foregroundColor of Text in SwiftUI?

Thanks for the answers in advance!

6条回答
  •  借酒劲吻你
    2021-02-08 13:15

    I guess that should help. Works with text, images and any other views.

    import SwiftUI
    
    // MARK: - API
    @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
    extension View {
        public func foreground(_ overlay: Overlay) -> some View {
            _CustomForeground(overlay: overlay, for: self)
        }
    }
    
    // MARK: - Implementation
    @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
    private struct _CustomForeground: 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)
        }
    }
    
    

    Personaly I like that approach the most. But also you can combine it into:

    import SwiftUI
    
    // MARK: - API
    @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
    extension View {
        public func foreground(_ overlay: Overlay) -> some View {
            self.overlay(overlay).mask(self)
        }
    }
    

    Usage example

提交回复
热议问题