How to set the size of an UIViewRepresentable?

我只是一个虾纸丫 提交于 2021-02-17 03:38:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!