ios 如何在键盘出现swiftUI时有条件地显示视图

2mbi3lxu  于 2023-06-25  发布在  iOS
关注(0)|答案(1)|浏览(124)

当我点击textField和键盘出现时,我想显示一个不同的视图。我尝试使用.onReceive修饰符沿着keyboardWillHide/ShowNotification属性,但是这些方法都没有一种能像预期的那样工作。下面是代码:

struct ContentView: View {
@State private var text = ""
var body: some View {
    
    VStack {
        Spacer()
        if //isKeyboardVisible - need to implement {
        {
            Text("Keyboard is shown")
        } else {
            VStack(alignment: .center, spacing: 16) {
                Text("Enter prompts")
                    .font(.custom("Avenir Next Medium", size: 18))
                    .foregroundColor(.white)
                    .padding(.trailing, 230)
                
                TextField(text: $text)
                    .frame(height: 120)
                    .cornerRadius(10)
                
                Text("create")
                    .opacity(text.isEmpty ? 0.4 : 1)
            }
            .padding(.horizontal)
        }
    }
}

}

irtuqstp

irtuqstp1#

@FocusState属性可以让你跟踪键盘何时显示,另一方面,如果用IF ELSE尝试这个,应用程序将崩溃,因为动画重叠和if else在swiftUI中的工作方式。这里有一个例子可以帮助你。

import SwiftUI

struct KeyboardView: View {
    
    @State private var text = ""
    @FocusState private var keyboardShown: Bool
    
    var body: some View {
        
        ZStack {
            Spacer()
            VStack(alignment: .center, spacing: 16) {
                Text("Enter prompts")
                    .font(.custom("Avenir Next Medium", size: 18))
                    .foregroundColor(.white)
                    .padding(.trailing, 230)
                
                TextField("Enter text", text: $text)
                    .frame(height: 120)
                    .cornerRadius(10)
                    .focused($keyboardShown)
                
                Text("create")
                    .opacity(text.isEmpty ? 0.4 : 1)
            }
            .padding(.horizontal)
            
            if keyboardShown
            {
                ZStack {
                    Color.blue.edgesIgnoringSafeArea(.all)
                    
                    Text("Keyboard is shown")
                        .onTapGesture {
                            keyboardShown = false
                        }
                }
            }
        }
 }
  }

相关问题