问题
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.
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?
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()
}
}
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.
I can't seem to find any documentation about how to layout a UIViewRepresentable.
What is the way to solve this?
回答1:
See: How does UIViewRepresentable size itself in relation to the UIKit control inside it?
struct SizeRepresentableTest: View {
var body: some View {
VStack {
SizeRepresentable().fixedSize()
Spacer()
}
}
}
来源:https://stackoverflow.com/questions/60868307/how-to-set-the-size-of-an-uiviewrepresentable