Skip to content

Instantly share code, notes, and snippets.

@chrisfsampaio
Created December 2, 2019 22:28
Show Gist options
  • Save chrisfsampaio/f7f151dbeb4a73dd9a65417608446e6b to your computer and use it in GitHub Desktop.
Save chrisfsampaio/f7f151dbeb4a73dd9a65417608446e6b to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
ListView()
.tabItem {
Text("First")
}
Text("hey")
.tabItem {
Text("Second")
}
}
.overlayPreferenceValue(TitlePreferenceKey.self) { titles in
VStack {
Text(titles.last ?? "")
Spacer()
}
}
}
}
struct ListView: View {
var body: some View {
NavigationView {
VStack(spacing: 36) {
NavigationLink(destination: DetailView()) {
Text("Push detail view1")
}
NavigationLink(destination: DetailView()) {
Text("Push detail view2")
}
NavigationLink(destination: DetailView()) {
Text("Push detail view3")
}
}
.testTitle("List View - Title")
}
}
}
struct DetailView: View {
var body: some View {
Text("Detail View")
.testTitle("Detail View - Title")
}
}
struct TitlePreferenceKey: PreferenceKey {
static var defaultValue: [String] = []
static func reduce(value: inout [String], nextValue: () -> [String]) {
let added = nextValue()
value.append(contentsOf: added)
}
}
struct TitleModifier: ViewModifier {
let title: String
func body(content: Content) -> some View {
return content
.transformPreference(TitlePreferenceKey.self) { value in
value.append(self.title)
}
}
}
extension View {
func testTitle(_ title: String) -> some View {
return modifier(TitleModifier(title: title))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment