Update UIViewRepresentable size from UIKit in SwiftUI

前端 未结 2 412
傲寒
傲寒 2021-01-12 14:25

I\'m embedding a view controller with variable-height UITextView inside a parent SwiftUI VStack and the view controller sizes it\'s frame to the whole screen be

相关标签:
2条回答
  • 2021-01-12 14:56

    Add fixedSize may solve this. .fixedSize(horizontal: false, vertical: true)

    0 讨论(0)
  • 2021-01-12 15:01

    Without being able to see more of your code, it's slightly difficult to say what the best solution would be, but based purely on this part of your question...

    I can get the correct size of the UITextView in didLayoutSubviews and pass it upwards to SwiftUI where it can be set properly - but where do I do that?

    I would suggest that you pass a binding property to your view controller that can be set to the calculated text view height, meaning that the view that contains your VStack would have a @State property like this:

    @State private var textViewHeight: CGFloat = 0
    

    You would then declare a @Binding property on your HighlighterVC and add an initializer like this:

    @Binding var textViewHeight: CGFloat
    
    init(textViewHeight: Binding<CGFloat>) {
        self._textViewHeight = textViewHeight
    }
    

    And then you would set textViewHeight to the calculated height in your didLayoutSubviews and add a .frame modifier to your HighlighterVC like this:

    VStack {
        HighlighterVC(textViewHeight: self.$textViewHeight)
            .frame(height: self.textViewHeight)
        Text("Tap and drag to highlight")
            .foregroundColor(.gray)
            .font(.caption)
    }
    

    Like I said at the beginning of my answer, this solution (that I believe would work, but since I can't test it, I'm not 100% certain) is based on your thoughts about what it is that you need. Without seeing more code, it's impossible for me to say if this is the best solution.

    0 讨论(0)
提交回复
热议问题