野瀬田*_* 裕樹 6 ios swift ios13 swiftui uihostingcontroller
我想根据通信结果更新 Swift UI View。但 UIHostingController.view 不适合 iOS 13 的 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
}
}
Run Code Online (Sandbox Code Playgroud)
仅适用于 iOS 13
尝试这个:
每次视图大小发生变化时,调用以下命令:
sampleView.view.removeFromSuperview()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
view.addArrangedSubview(hosting.view)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5082 次 |
| 最近记录: |