我有一个基本的SwiftUI组件。
struct PopupModal: View {
var body: some View {
Text("Hello, World!")
}
}
struct PopupModal_Previews: PreviewProvider {
static var previews: some View {
PopupModal()
}
}
我有一个UIViewController
,我想实例化此组件并显示它。
private let _popup = PopupModal()
private lazy var _popupController = UIHostingController(rootView: _popup)
override public func viewDidLoad() {
// ...
self.addChild(_popupController)
view.addSubview(_popupController.view)
_popupController.didMove(toParent: self)
}
override public func viewDidLayoutSubviews() {
// How do I make this automatic or as a function of the size of _popup?
let popupHeight = CGFloat(260)
_popupController.view.frame = CGRect(x: 15, y: view.bounds.height - popupHeight - 20, width: view.bounds.width - 30, height: popupHeight)
}
显示了PopupModal
,但是我正在手动调整其高度。怎么能
我是根据内容大小来确定大小的吗?
答案 0 :(得分:2)
您可以使用
_popupController.view.sizeToFit()
为使视图最初适合其固有内容,并在添加到Superview后使用自动布局约束按需对其进行布局。