【SwiftUI】(その2) ZStack構成のViewの配置で、ignoreSafeAreaとキーボード回避について

前回の記事でGemetory Readerを利用したコードを記載しましたが、利用せずに、ZStackのViewでキーボード回避ができることがわかったので以下にコードを掲載します。

サンプルコード

上記の例で利用したコードです
import SwiftUI
struct ContentView: View {
@State var text = ""
var body: some View {
ZStack {
// 背景
VStack(spacing:1) {
Color.yellow
}
.ignoresSafeArea(.keyboard, edges: .all)
//↓↓ ScrollViewを利用しないと、上に配置したListのキーボード回避の挙動の影響をうけるため、ScrollViewとした
ScrollView(.vertical){
VStack {
Spacer()
TextField("入力してください",
text: $text)
.font(.system(size: 18))
.foregroundColor(Color.black)
.background(Color.white)
.border(.black, width: 1)
.frame(height: 50)
Spacer().frame(height: 100)
}.frame(width: 330)
.background(Color.gray)
.frame(height: UIScreen.main.bounds.height)
}
// リフトアップする
VStack {
List {
ForEach(0 ..< 30) { i in
TextField("item+\(i)",text: $text )
}
}
.onTapGesture(perform: {
UIApplication.shared.closeKeyboard()
})
}.frame(width: 200)
}
.onTapGesture(perform: {
UIApplication.shared.closeKeyboard()
})
.ignoresSafeArea(.container,edges: .all)
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

このブログの人気の投稿

アプリアイコンの素材探し

【SwiftUI】グラスモーフィズムを試してみました

【SwiftUI】LazyVGridについて