0

我的目标是在键盘可见时在 SwiftUI iOS 应用程序的导航栏中显示一个按钮,并在键盘不可见时隐藏它。我可以使用视图主体内的按钮使其工作,但导航栏中的任何内容都不会响应我的@State变量。

这是一个示例项目:

struct ContentView: View {
  @State var showDone = false
  @State var text = "Testing"
  
  var body: some View {
    ZStack{
      NavigationView {
          
        VStack{
          ZStack{}
          .toolbar{
            ToolbarItem(placement: .principal) {
              Text("Nav Bar")
            }
            ToolbarItem(placement: .navigationBarTrailing) {
              Button(action: {
                hideKeyboard()
              }){
                Text("Hide A")
              }
              .opacity(showDone ? 1 : 0) //<-- This doesn't work
            }
          }

          //This is just for showing the keyboard when focused
          TextField("", text: $text)
            .textFieldStyle(RoundedBorderTextFieldStyle())

          //This button works correctly
          Button(action: {
            hideKeyboard()
          }){
            Text("Hide B")
          }
          .opacity(showDone ? 1 : 0)
        }
        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
          print("keyboard showing")
          showDone = true
        }
        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
          print("keyboard hidden")
          showDone = false
        }
      }
    }
  }
}

我有一个隐藏键盘的全局函数:

//Global function for hiding the keyboard
extension View {
  func hideKeyboard() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
  }
}

我尝试将opacity修饰符放在Text("Hide A")ButtonToolbarItem本身上,但它们都不起作用(ToolbarItem编译器不允许将其放在 上)。

有没有人遇到过导航栏的东西不响应@State变量?

4

1 回答 1

0

我想我是如此专注于让修饰符起作用,以至于我没有想到另一个明显的选择。这工作正常:

ToolbarItem(placement: .navigationBarTrailing) {
  if showDone{
    Button(action: {
      hideKeyboard()
    }){
      Text("Hide A")
    }
  }
}
于 2021-03-07T00:14:42.687 回答