Skip to content

Instantly share code, notes, and snippets.

@paulweichhart
Last active October 16, 2019 22:08
Show Gist options
  • Save paulweichhart/e0288e1ca482018820054385e2d90046 to your computer and use it in GitHub Desktop.
Save paulweichhart/e0288e1ca482018820054385e2d90046 to your computer and use it in GitHub Desktop.
SwiftUI Re-rendering
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