設定 SwiftUI Text、TextField、TextEditor 的文字對齊

以下假設 iOS 的系統語言是由左到右,因此 leading 表示左邊,trailing 是右邊。

Text

框框預設剛好等於文字的大小。

struct ContentView: View {
var body: some View {
Text("Dreams do come true")
.border(.black)
}
}

當文字內容小於框框寬度時,Text 會在 frame 的框框裡置中。

struct ContentView: View {
var body: some View {
Text("Dreams do come true")
.frame(width: 300)
.border(.black)
}
}

在 frame 裡設定 alignment,.leading 讓文字靠左。

struct ContentView: View {
var body: some View {
Text("Dreams do come true")
.frame(width: 300, alignment: .leading)
.border(.black)
}
}

透過 multilineTextAlignment 設定多行文字的對齊。

struct ContentView: View {
var body: some View {
Text("Dreams do come true, if only we wish hard enough. You can have anything in life if you will sacrifice everything else for it.")
.multilineTextAlignment(.center)
.border(.black)
.padding()
}
}

多行文字的內容小於 frame 的寬度,文字會在框框裡置中,文字靠左對齊。

struct ContentView: View {
var body: some View {
Text("Dreams do come true,\nif only we wish hard enough.")
.frame(width: 300)
.border(.black)
.padding()
}
}

frame 讓文字在框框裡置右,multilineTextAlignment 讓文字靠右對齊。

struct ContentView: View {
var body: some View {
Text("Dreams do come true,\nif only we wish hard enough.")
.frame(width: 300, alignment: .trailing)
.multilineTextAlignment(.trailing)
.border(.black)
.padding()
}
}

TextField

TextField 的文字預設會在框框裡置左。

struct ContentView: View {
@State private var name = ""
var body: some View {
TextField("name", text: $name)
.textFieldStyle(.roundedBorder)
.padding()
}
}

透過 multilineTextAlignment 設定文字的對齊。

struct ContentView: View {
@State private var name = ""
var body: some View {
TextField("name", text: $name)
.textFieldStyle(.roundedBorder)
.multilineTextAlignment(.center)
.padding()
}
}

多行文字也一樣,用 multilineTextAlignment 對齊。

struct ContentView: View {
@State private var name = "peter\npan"
var body: some View {
TextField("name", text: $name, axis: .vertical)
.lineLimit(2)
.frame(width: 200)
.multilineTextAlignment(.center)
.textFieldStyle(.roundedBorder)
.padding()
}
}

TextEditor

跟 TextField 一樣,文字預設會在框框裡置左,用 multilineTextAlignment 設定文字的對齊。

struct ContentView: View {
@State private var name = "peter\npan"
var body: some View {
TextEditor(text: $name)
.frame(width: 200, height: 100)
.multilineTextAlignment(.center)
.border(Color.black)
.padding()
}
}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com