I have a swiftUI view using UIViewRepresentable to show an ActiveLabel I have a .frame() modifier on that ActiveLabel which has a height which is reflected by a @State variable. When this height is updated the frame height does not always seem to update. Am I doing anything obvious wrong.
Here is a simplified version of my setup, let me know if if it would be usefl to include more of my solution.
let text:String
let mentions: [String: String]
let lineLimit:Int?
@State private var height: CGFloat = .zero
var body: some View {
ActiveLabelWrapper(
text: text,
lineLimit: lineLimit,
height: $height,
handleHashtagTap: {hashtag in print(hashtag)},
handleMentionTap: {username in print(username)}
).frame(minHeight: height)
}
Here is the ActiveLabelWrapper:
enter cstruct ActiveLabelWrapper: UIViewRepresentable {
let text: String
let lineLimit: Int?
@Binding var height: CGFloat
let handleHashtagTap: (String) -> Void
let handleMentionTap: (String) -> Void
func makeUIView(context: Context) -> ActiveLabel {
let label = ActiveLabel()
label.enabledTypes = [.mention, .hashtag]
label.text = text
...
label.numberOfLines = lineLimit ?? 0
label.adjustsFontSizeToFitWidth = false
label.lineBreakMode = .byTruncatingTail
label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
label.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
label.setContentHuggingPriority(.defaultHigh, for: .horizontal)
return label
}
func updateUIView(_ uiView: ActiveLabel, context: Context) {
uiView.text = text
DispatchQueue.main.async {
height = uiView.sizeThatFits(CGSize(width: uiView.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
}
}
This code seems to work most of the time when using the ios simulator (not all the time) but when I open the app on my physical device the height is not updated once the ActiveLabel text is created, instead it shows only a single line of text rather than all of the lines.
For some more context, the reason I believe the problem lies within the frame height not updating is that I have confirmed the ui.sizeThatFits(…) is returning the correct value. And even if I manually update the size with an .onAppear() or .task() the frame height never changes.
What am I missing? I have tried a lot and nothing has worked, so any help is appreciated.