gpt4 book ai didi

ios - UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI

转载 作者:行者123 更新时间:2023-12-01 16:01:09 25 4
gpt4 key购买 nike

假设你有一个 UIKit View 想要决定它自己的大小(通过 intrinsicContentSize 或布局约束,大小可能会改变)。例如:

/// Some UIKit view that wants to have a specific size
class YellowBoxUIKitView : UIView {

init() {
super.init(frame: .zero)
self.backgroundColor = .yellow
}

required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported")
}

override var intrinsicContentSize: CGSize {
return CGSize(width: 100, height: 100)
}

}

如何将其包装为 SwiftUI UIViewRepresentable 并使其自动将 UIView 大小传递给 SwiftUI?

struct YellowBoxView : UIViewRepresentable {

func makeUIView(context: Context) -> YellowBoxUIKitView {
// TODO: How do you pass the size from UIKit up to SwiftUI?
YellowBoxUIKitView()
}

func updateUIView(_ uiView: YellowBoxUIKitView, context: Context) {
}

}

SwiftUI 不尊重 UIView 的大小,只是给它最大可能的宽度/高度。

可运行示例: SizedUIViewRepresentableView

这里有一个关于 UITextView 的类似问题: Update UIViewRepresentable size from UIKit in SwiftUI

最佳答案

解决方案是为表示的 UIView 显式设置压缩/拥抱优先级

使用 Xcode 11.4/iOS 13.4 测试

struct YellowBoxView : UIViewRepresentable {

func makeUIView(context: Context) -> YellowBoxUIKitView {
let view = YellowBoxUIKitView()

view.setContentHuggingPriority(.required, for: .horizontal) // << here !!
view.setContentHuggingPriority(.required, for: .vertical)

// the same for compression if needed

return view
}

func updateUIView(_ uiView: YellowBoxUIKitView, context: Context) {
}
}

关于ios - UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61832221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com