我的目标是在键盘可见时在 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")
、Button
和ToolbarItem
本身上,但它们都不起作用(ToolbarItem
编译器不允许将其放在 上)。
有没有人遇到过导航栏的东西不响应@State
变量?