[英]SwiftUI - NavigationLink and NavigationStack is not working with a button for iOS 16
[英]SwiftUI - NavigationLink is not working with a button
我正在制作一個應用程序,我在其中輸入兩個數字,並希望在單擊按鈕時在第二個屏幕中顯示數字的加法結果。 我可以在控制台中打印結果,但不幸的是,按鈕周圍的導航鏈接似乎不起作用。 如果我將 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)")
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.