はじめに
SwiftUIのTextのドキュメントを読んでみた内容(超基本的なこと)をまとめました
環境
Xcode 13.4.1
内容
テキストを表示させる
Text()
を使って文字列を表示
@frozen struct Text
init<S>(_ content: S) where S : StringProtocol
Text(someString) // Displays the contents of `someString` without localization.
フォントを変える
func font(_ font: Font?) -> some View
を使う
VStack {
Text("Font applied to a text view.")
.font(.largeTitle)
VStack {
Text("These 2 text views have the same font")
Text("applied to their parent hierarchy")
}
}
.font(.system(size: 16, weight: .light, design: .default))

フォントの種類
.largeTitle
: 大きなタイトル
.title
: タイトル
.title2
: 第2階層見出し
.title3
: 第3階層見出し
.headline
: 見出しテキスト
.subheadline
: 小見出し
.body
: 本文テキスト
.callout
: コールアウト
.caption
: キャプション
.caption2
: 代替キャプション
.footnote
: 脚注
フォントをもっと細かく変える
.system
を使いより細かく指定できたり、.bold
や.italic
なども使える
Text("by William Shakespeare")
.font(.system(size: 12, weight: .light, design: .serif))
.italic()
制約を加える
func frame( width: CGFloat? = nil, height: CGFloat? = nil, alignment: Alignment = .center ) -> some View
によって制約をつけることができる
Alignment
の指定もいろいろできる
Text("To be, or not to be, that is the question:")
.frame(width: 100)
行数の指定をする
.lineLimit
で行数の指定ができる
Text("Brevity is the soul of wit.")
.frame(width: 100)
.lineLimit(1)
ローカライズさせる
Text("pencil")
だけでローカライズされるが、あえてさせたくない場合は、Text(verbatim: "pencil")
を使う
変数をローカライズさせる場合はText(LocalizedStringKey(writingImplement))
とする
※ init(_:tableName:bundle:comment:)
Text("pencil") // Searches the default table in the main bundle.
Text(verbatim: "pencil") // Displays the string "pencil" in any locale.
// Don't localize a string variable...
Text(writingImplement)
// ...unless you explicitly convert it to a localized string key.
Text(LocalizedStringKey(writingImplement))
おわりに
やれることは他にもたくさんあるとは思いますが、まずはドキュメントに書いてある基本的なことを理解してから、幅広く調べていこうと思います
参考