この記事では、SwiftUIで一部の文字の装飾する方法を解説していきたいと思います。

例えば、このような感じです。
やり方は以下の2パターンありますので、それぞれ解説していきたいと思います。
- Textを連結する方法
- AttributedStringを使う方法
Textを連結する方法
こちらは、単純です。Text()を+でくっつけるだけです。
struct ContentView: View {
var body: some View {
Text("SwiftUIで") +
Text("一部の文字").foregroundColor(.red).fontWeight(.bold) +
Text("だけを装飾する。")
}
}
ただ、このやり方だと取得した文字列を表示する時とか柔軟に対応できません。。
AttributedStringを使う方法
こちらの方法は、String型ではなく、AttributedString型を使います。関数を作って文字列を渡してあげます。今回は、"一部の文字"と一致している箇所を変更していますが、ここの処理を変更すると、いろいろな状況に対応できます。
struct ContentView: View {
var body: some View {
Text(getAttributedString("SwiftUIで一部の文字だけを装飾する。"))
}
func getAttributedString(_ str: String) -> AttributedString {
var attributedString = AttributedString(str)
if let range = attributedString.range(of: "一部の文字") {
attributedString[range].foregroundColor = .red
attributedString[range].font = .system(size: 17, weight: .bold)
}
return attributedString
}
}

