我想根据通讯结果更新 Swift UI View。但是 UIHostingController.view 不适合 iOS 13 的 rootView 大小。当我尝试使用下面的示例代码时,也会发生同样的事情。我想将自调整大小的 SwiftUI 视图添加到 UIStackView,但是由于这个问题,SwiftUI 视图与上一个和下一个视图重叠。我怎样才能避免这个问题?
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
}
}
如果像下面这样 addSubview 到 UIStackView,iOS13 中 Swift UI View 的高度不会改变。