Last active
October 16, 2019 22:08
-
-
Save paulweichhart/e0288e1ca482018820054385e2d90046 to your computer and use it in GitHub Desktop.
SwiftUI Re-rendering
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 Foundation | |
import PlaygroundSupport | |
import SwiftUI | |
// This View will be re-rendered because it's property value changed | |
struct Headline: View { | |
var headline: String | |
var body: some View { | |
Text(headline) | |
.foregroundColor(Color(red: 0.12, green: 0.73, blue: 0.82)) | |
.font(.headline) | |
.padding(EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 0)) | |
} | |
} | |
// This View won't be re-rendered since it didn't change | |
struct SubHeadline: View { | |
var subHeadline: String | |
var body: some View { | |
Text(subHeadline + " " + Date().description(with: .current)) | |
.lineLimit(nil) | |
.font(.subheadline) | |
} | |
} | |
struct Content: View { | |
@ObservedObject var viewModel: ViewModel | |
var text: String | |
var headline: String | |
var subHeadline: String | |
var body: some View { | |
HStack { | |
VStack(alignment: .leading) { | |
Headline(headline: "\(headline) \(viewModel.counter)") | |
SubHeadline(subHeadline: subHeadline) | |
Text(text) | |
.foregroundColor(viewModel.counter % 2 == 0 ? .black : .gray) | |
Spacer() | |
}.padding(20) | |
Spacer() | |
} | |
} | |
} | |
final class ViewModel: ObservableObject { | |
@Published var counter = 0 | |
init() { | |
startTimer() | |
} | |
func startTimer() { | |
Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { _ in | |
self.counter += 1 | |
}) | |
} | |
} | |
PlaygroundPage.current.liveView = UIHostingController(rootView: Content(viewModel: ViewModel(), text: "The future is reactive", headline: "High performance SwiftUI", subHeadline: "by Paul Weichhart")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment