Forked from gongzhang/swiftui-inline-modifier.swift
Created
October 20, 2020 11:51
-
-
Save NeverwinterMoon/f5056a88e3e3cfdaec15cf5fb9189125 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import PlaygroundSupport | |
/// `InlineModifier` helps you apply a view modifier in a inline block. | |
public struct InlineModifier<R: View>: ViewModifier { | |
private let block: (Content) -> R | |
public init(@ViewBuilder _ block: @escaping (Content) -> R) { | |
self.block = block | |
} | |
public func body(content: Content) -> some View { | |
block(content) | |
} | |
} | |
extension View { | |
public func modifier<T: View>(@ViewBuilder _ block: @escaping (AnyView) -> T) -> some View { | |
self.modifier(InlineModifier<T>({ (content: InlineModifier<T>.Content) in | |
block(AnyView(content)) | |
})) | |
} | |
} | |
/// # Demo | |
struct ContentView: View { | |
var body: some View { | |
NavigationView { | |
List { | |
Text("Hello") | |
} | |
.modifier { | |
// inline availability check for modifiers ✌️ | |
if #available(iOS 14.0, *) { | |
$0.listStyle(InsetGroupedListStyle()) | |
} else { | |
$0.listStyle(GroupedListStyle()) | |
.environment(\.horizontalSizeClass, .regular) | |
} | |
} | |
.navigationTitle("Demo") | |
} | |
} | |
} | |
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment