自動避開鍵盤的 SwiftUI TextField & TextEditor

在 iOS 14,SwiftUI 的 TextField & TextEditor 變得更厲害了。當鍵盤出現時,App 畫面將自動上移,我們再也不怕鍵盤檔到輸入的文字了。

無捲動頁面的 TextField

struct ContentView: View {
@State private var name = ""
var body: some View {
VStack {
Image("水瓶")
.resizable()
.scaledToFill()
.frame(width: 300, height: 300)
.clipShape(Circle())
TextField("最棒的星座", text: $name) .textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 200)
}

}
}

ScrollView 的 TextField

struct ContentView: View {
@State private var name = ""
var body: some View {
ScrollView {
VStack(spacing: 100) {
Image("水瓶")
.resizable()
.scaledToFill()
.frame(width: 400, height: 400)
.clipShape(Circle())
Image("金牛")
.resizable()
.scaledToFill()
.frame(width: 400, height: 400)
.clipShape(Circle())
TextField("最棒的星座", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 200)
}
}

}
}

多行文字的 TextEditor

struct ContentView: View {
@State private var message = "愛要怎麼說"
var body: some View {
VStack {
Image("愛要怎麼說")
.resizable()
.scaledToFill()
.frame(width: 200, height: 200)
.clipShape(Circle())
TextEditor(text: $message)
.frame(width: 200, height: 200)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2))
}

}
}

支援 List & Form

List & Form 裡的 TextField & TextEditor 也會自動避開鍵盤。

struct ContentView: View {
@State private var name = ""
var body: some View {

Form {
Image("水瓶")
.resizable()
.scaledToFill()
.frame(width: 300, height: 300)
.clipShape(Circle())
Image("金牛")
.resizable()
.scaledToFill()
.frame(width: 300, height: 300)
.clipShape(Circle())
TextField("最棒的星座", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())

}
}
}

--

--

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

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