Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does UIViewRepresentable take all of the available space? [duplicate]

Tags:

ios

swift

swiftui

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?

like image 941
Kristof Van Landschoot Avatar asked Dec 07 '25 07:12

Kristof Van Landschoot


1 Answers

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()
        }
    }
}
like image 161
Obliquely Avatar answered Dec 08 '25 20:12

Obliquely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!