From 0e811cb14de367bbd58a94d12259687e5ee08bea Mon Sep 17 00:00:00 2001 From: Andy Kayley Date: Fri, 28 Oct 2022 15:12:45 +0100 Subject: [PATCH] Fix Publishing changes from within view updates is not allowed, this will cause undefined behavior. (#25) Co-authored-by: Andy Kayley --- Sources/AttributedText/AttributedText.swift | 10 +++++++--- Sources/AttributedText/TextSizeViewModel.swift | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/Sources/AttributedText/AttributedText.swift b/Sources/AttributedText/AttributedText.swift index 15513e1..15e8d36 100644 --- a/Sources/AttributedText/AttributedText.swift +++ b/Sources/AttributedText/AttributedText.swift @@ -2,7 +2,8 @@ import SwiftUI /// A view that displays styled attributed text. public struct AttributedText: View { - @StateObject private var textSizeViewModel = TextSizeViewModel() + private var textSizeViewModel = TextSizeViewModel() + @State private var textSize: CGSize? private let attributedText: NSAttributedString private let onOpenLink: ((URL) -> Void)? @@ -36,10 +37,13 @@ public struct AttributedText: View { ) } .frame( - idealWidth: textSizeViewModel.textSize?.width, - idealHeight: textSizeViewModel.textSize?.height + idealWidth: textSize?.width, + idealHeight: textSize?.height ) .fixedSize(horizontal: false, vertical: true) + .onReceive(textSizeViewModel.$textSize) { size in + textSize = size + } } } diff --git a/Sources/AttributedText/TextSizeViewModel.swift b/Sources/AttributedText/TextSizeViewModel.swift index 8f2dc62..a43f7d4 100644 --- a/Sources/AttributedText/TextSizeViewModel.swift +++ b/Sources/AttributedText/TextSizeViewModel.swift @@ -1,6 +1,6 @@ import SwiftUI -final class TextSizeViewModel: ObservableObject { +final class TextSizeViewModel { @Published var textSize: CGSize? func didUpdateTextView(_ textView: AttributedTextImpl.TextView) {