Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?
@noppefoxwolf

[SwiftUI]UIViewRepresentableのプレビューでsizeThatFitを有効にする

More than 1 year has passed since last update.

SwiftUIでUIKitのコンポーネントを利用する場合、UIViewRepresentableを利用します。

TextView.swift
import SwiftUI

struct Label: View {
    var body: some View {
        InternalUILabel()
    }
}

private struct InternalUILabel: UIViewRepresentable {
    typealias UIViewType = UILabel

    func makeUIView(context: UIViewRepresentableContext<InternalUILabel>) -> UIViewType {
        let label = UILabel()
        label.text = "hello world"
        return label
    }

    func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<InternalUILabel>) {

    }
}

struct Label_Previews: PreviewProvider {
    static var previews: some View {
        Label().previewLayout(.sizeThatFits)
    }
}

Screen Shot 2019-10-05 at 16.30.36.png

この状態でプレビューを表示すると、previewLayoutを指定しても上記のように画面いっぱいに表示されます。

プレビューでsizeThatFitsを有効にするには、UIViewRepresentableで返すcontentHuggingの優先度を上げて返してあげる必要があります。

func makeUIView(context: UIViewRepresentableContext<InternalUILabel>) -> UIViewType {
        let label = UILabel()
        label.text = "hello world"
        label.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        label.setContentHuggingPriority(.defaultHigh, for: .vertical)
        return label
}

Screen Shot 2019-10-05 at 16.33.46.png

この手法が使えるのは返すUIViewのintrinsicContentSizeがある場合なので、決定しない場合はサブクラスなどを作ってintrinsicContentSizeをoverrideする必要がありそうです。

4
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
noppefoxwolf
きつねすき、にんげんこわい

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
4
Help us understand the problem. What is going on with this article?