LoginSignup
0
1

More than 1 year has passed since last update.

SwiftUIで文中に画像を入れたいとき

Last updated at Posted at 2022-07-17

iOS14以降であれば、以下のように書くことで Text を使ってテキストと画像をひとかたまりの View として表示できます。

Text("Moon \(Image(systemName: "moon"))")

テキストと画像が混在したものを 動的 に作り出したい場合、以下のように LocalizedStringKey を生成する必要があります。

import SwiftUI

struct Item {
    let label: String
    let symbol: String
}

struct ContentView: View {
    let items: [Item]

    var body: some View {
        Text(string())
            .font(.system(size: 40))
            .foregroundColor(.blue)
    }
    
    private func string() -> LocalizedStringKey {
        // LocalizedStringKey.StringInterpolationでフォーマット
        var interpolation = LocalizedStringKey.StringInterpolation(literalCapacity: 100, interpolationCount: items.count * 2)
        items.forEach { item in
            interpolation.appendInterpolation(Image(systemName: item.symbol))
            interpolation.appendInterpolation("\(item.label) ")
        }
        return .init(stringInterpolation: interpolation)
    }
}

struct ContentView_Previews: PreviewProvider {
    private static let items: [Item] = [
        .init(label: "Sun", symbol: "sun.max"),
        .init(label: "Moon", symbol: "moon"),
        .init(label: "Globe", symbol: "globe")
    ]

    static var previews: some View {
        ContentView(items: items)
    }
}

ちなみに Text+ で連結することもできるので、以下のようにもできます。

    private func text() -> Text {
        return items.reduce(Text("")) { text, item in
            return text + Text(Image(systemName: item.symbol)) + Text("\(item.label) ")
        }
    }

折り返しにも対応できていいですね!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1