LoginSignup
3

More than 1 year has passed since last update.

【SwiftUI】Textに一部だけ背景色を付ける

Posted at

はじめに

Text内でスタイルを変えないといけない場面に遭遇して、こんな方法があるんだと思ったことがあったので記録しておきます。

やりたいデザイン

テキストが折り返されても最初の行から始めたい(伝われ)
これはHStackでは実現できません。
simulator_screenshot_5AE81043-1425-4BDC-8827-9336376CC50F.png

実装方法

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text(makeAttributedStringText(text: "重要 明日は面談あり明日は面談あり明日は面談あり明日は面談あり明日は面談あり明日は面談あり"))
            Text(makeAttributedStringText(text: "確認 配布資料を持つ配布資料を持つ配布資料を持つ配布資料を持つ配布資料を持つ配布資料を持つ"))
            Text(makeAttributedStringText(text: "重要 目覚ましをかける目覚ましをかける目覚ましをかける目覚ましをかける目覚ましをかける"))
            Text(makeAttributedStringText(text: "注意 明日は6時半起き明日は6時半起き明日は6時半起き明日は6時半起き明日は6時半起き明日は6時半起き"))
        }

    }

    func makeAttributedStringText(text: String) -> AttributedString {
        var attributed = AttributedString(text)

        if let range = attributed.range(of: "確認") {
            attributed[range].foregroundColor = .white
            attributed[range].backgroundColor = .green
            attributed[range].font = .headline
        } else if let range = attributed.range(of: "重要") {
            attributed[range].foregroundColor = .white
            attributed[range].backgroundColor = .red
            attributed[range].font = .headline
        } else if let range = attributed.range(of: "注意") {
            attributed[range].foregroundColor = .white
            attributed[range].backgroundColor = .yellow
            attributed[range].font = .headline
        }

        return attributed
    }
}

おわり

やりたいことができてよかったです

参考記事

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
3