我希望根据通信结果更新Swift UI视图。 但是在iOS 13上,UIHostingController.view与rootView大小不匹配。 当我尝试使用下面的示例代码时,同样的事情发生了。 我想将自适应大小的SwiftUI View添加到UIStackView中,但是由于这个问题,SwiftUI View会重叠在前一个和后一个视图上。 我该如何避免这个问题?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = SampleObject()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
hosting.view.backgroundColor = UIColor.green
addChild(hosting)
view.addSubview(hosting.view)
hosting.view.translatesAutoresizingMaskIntoConstraints = false
hosting.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
hosting.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
hosting.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hosting.didMove(toParent: self)
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
object.test()
}
}
}
struct SampleView: View {
@ObservedObject var object: SampleObject
var body: some View {
VStack {
Text("test1").background(Color.blue)
Text("test2").background(Color.red)
if object.state.isVisibleText {
Text("test2").background(Color.gray)
}
}
.padding(32)
.background(Color.yellow)
}
}
final class SampleObject: ObservableObject {
struct ViewState {
var isVisibleText: Bool = false
}
@Published private(set) var state = ViewState()
func test() {
state.isVisibleText = true
}
}
如果将子视图添加到UIStackView中,如下所示,在iOS13中Swift UI View的高度将不会改变。
![enter image description here](https://istack.dev59.com/hOtGv.webp)
![enter image description here](https://istack.dev59.com/0Jp1j.webp)
![enter image description here](https://istack.dev59.com/69sln.webp)