自動避開鍵盤的 SwiftUI TextField & TextEditor
Published in
Jul 28, 2020
在 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())
}
}
}