一段時間以來,我一直在為此撓頭。UIHostingController在將視圖添加到視圖控制器時,我注意到我的布局略有偏差。考慮最簡單的例子:
import SwiftUI
struct SquareView: View {
var body: some View {
Rectangle()
.foregroundColor(.orange)
.frame(width: 50.0, height: 50.0)
}
}
struct SquareView_Previews: PreviewProvider {
static var previews: some View {
SquareView()
}
}
現在在視圖控制器中:
import UIKit
import SwiftUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let squareView = SquareView()
let hostingController = UIHostingController(rootView: squareView)
addChild(hostingController)
hostingController.didMove(toParent: self)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let leading = hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant:32.0)
let top = hostingController.view.topAnchor.constraint(equalTo: view.topAnchor, constant: 32.0)
NSLayoutConstraint.activate([leading, top])
// Wait some time for the layout
DispatchQueue.main.asyncAfter(deadline: .now() 2.0) {
// Now the size is correct!
hostingController.view.invalidateIntrinsicContentSize()
}
}
}
最初添加到視圖時,內在內容大小將不正確(藍色邊框是內在大小):

32.0這導致我的視??圖看起來比固定在頂部時的插圖更大。
如果我等待布局并呼叫hostingController.view.invalidateIntrinsicContentSize()大小將正確更新:

現在我知道我可以使用DispatchQueue.main.async而不是延遲,這將適用于這個布局。但在某些情況下使用DispatchQueue.main.async不起作用,因為布局還沒有準備好。請注意,呼叫也不是解決方案,因為它會創建一個無限回圈hostingController.view.invalidateIntrinsicContentSize。viewDidLayoutSubviews
這似乎完全是瘋狂的,這不能開箱即用。我在這里錯過了什么嗎?如何intrinsicContentSize正確設定?
uj5u.com熱心網友回復:
與其添加延遲來等待布局發生,不如通過呼叫來要求它立即發生怎么樣layoutIfNeeded?
// do this after activating constraints
view.layoutIfNeeded()
請注意,它被稱為 on view,而不是hostingController.view。這很重要,因為正方形不需要布置任何東西——它self.view需要布置正方形。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486936.html
