如何解决SwiftUI-NavigationLink无法使用按钮
我正在制作一个应用程序,其中我需要输入两个数字,并希望在单击按钮时在第二个屏幕中显示数字的加法结果。我可以在控制台中打印结果,但是不幸的是,按钮周围的导航链接似乎无效。如果我将NavigationLink放在按钮标签周围而不是整个按钮周围,那么它将转到第二个屏幕,但是按钮动作将停止工作。这是我的代码:
import SwiftUI
struct ContentView: View {
@State private var number1 : String = ""
@State private var number2: String = ""
@State private var isTapped:Bool = false
@State var sum : Double = 0
var body: some View {
NavigationView {
VStack{
TextField("Type first number",text: $number1)
.keyboardType(.numberPad).padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.background(Color.gray).border(Color.blue,width:5)
TextField("Type second number",text: $number2)
.keyboardType(.numberPad).padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.background(Color.gray).border(Color.blue,width:5)
//this Navigationlink is not working
NavigationLink(destination: Text("\(self.sum)")) {
Button(action: {
print("I am here in the action")
self.isTapped.toggle()
UIApplication.shared.endEditing()
if let num1 = Double(self.number1),let num2 = Double(self.number2){
print("I am here")
self.sum = num1 + num2
print("\(self.sum)")
}
}) {
//If I put the Navigationlink here,button action stop working.
Text("Add Two Numbers")
.padding()
.foregroundColor(.blue)
.background( isTapped ? Color.orange : Color.gray)
.font(.title)
.border(Color.blue,width: 5)
.shadow(radius: 10)
}
}
}
}
}
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder),to: nil,from: nil,for: nil)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
有任何线索吗?感谢您的好奇心。
解决方法
实际上,
NavigationLink
本身就是一个按钮,因此您会引入某种冲突。相反,您可以仅将链接与其他点击手势处理程序一起使用,例如
NavigationLink(destination: Text("\(self.sum)")) {
Text("Add Two Numbers")
.padding()
.foregroundColor(.blue)
.background(isTapped ? Color.orange : Color.gray)
.font(.title)
.border(Color.blue,width: 5)
.shadow(radius: 10)
}
.simultaneousGesture(TapGesture().onEnded{
print("I am here in the action")
self.isTapped.toggle()
UIApplication.shared.endEditing()
if let num1 = Double(self.number1),let num2 = Double(self.number2){
print("I am here")
self.sum = num1 + num2
print("\(self.sum)")
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。