如何设置UIViewRepresentable的大小? [英] How to set the size of an UIViewRepresentable?
问题描述
我的想法是这样的:无论SwiftUI尚未提供什么,都可以使用UIViewRepresentable来解决.因此,我着手为TTTAttributedLabel制作一个UIViewRepresentable.
The idea, I thought, was this: whatever is not provided yet in SwiftUI, one can get around using UIViewRepresentable. So I set out to make a UIViewRepresentable for TTTAttributedLabel.
但是API中缺少一些基本知识,或者我缺少一些基本知识:如何设置UIViewRepresentable的内在内容大小"?
But there is something basic missing in the API, or I am missing something basic: how can one set the "intrinsic content size" of the UIViewRepresentable?
很像SwiftUI Text
,我希望我的组件能够根据容器的大小将其自身设置为一定的大小.
Much like a SwiftUI Text
, I would want my component to be able to set itself to a certain size considering the size of its container.
我的第一个想法是使用固有内容大小,所以我创建了这个:
My first idea was to use intrinsic content sizes, so I created this:
class SizeRepresentableView: UILabel {
override init(frame: CGRect) {
super.init(frame: CGRect.zero)
text="hello"
backgroundColor = UIColor.systemYellow
}
override var intrinsicContentSize: CGSize {
return CGSize(width: 100, height: 100)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct SizeRepresentable: UIViewRepresentable {
func updateUIView(_ uiView: SizeRepresentableView, context: Context) {
}
typealias UIViewType = SizeRepresentableView
func makeUIView(context: UIViewRepresentableContext<SizeRepresentable>) -> SizeRepresentableView {
let v = SizeRepresentableView(frame: CGRect.zero)
return v
}
}
struct SizeRepresentableTest: View {
var body: some View {
VStack {
SizeRepresentable()
Spacer()
}
}
}
struct SizeRepresentable_Previews: PreviewProvider {
static var previews: some View {
SizeRepresentableTest()
}
}
但这不起作用.标签占用了所有空间,间隔符则没有.使用SwiftUI Text
而不是我的 SizeRepresentable
,标签可以整齐地排列在顶部,并且分隔符会占据所有空间.
but that does not work. The label takes up all the space, the spacer none. With a SwiftUI Text
instead of my SizeRepresentable
the label is neatly arranged on top and the spacer takes up all the space, as it should.
我似乎找不到任何有关如何布局UIViewRepresentable的文档.
I can't seem to find any documentation about how to layout a UIViewRepresentable.
解决这个问题的方法是什么?
What is the way to solve this?
推荐答案
请参阅: 查看全文