【SwiftUI】(その2) ZStack構成のViewの配置で、ignoreSafeAreaとキーボード回避について
前回の記事でGemetory Readerを利用したコードを記載しましたが、利用せずに、ZStackのViewでキーボード回避ができることがわかったので以下にコードを掲載します。
サンプルコード
上記の例で利用したコードです
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |