欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SwiftUI NavigationView页面之间传参数

程序员文章站 2024-03-24 12:41:52
...

在做SwiftUI开发时,想要数据在两个页面View之间传递,通常采用NavigationView加NavigationLink跳转的方式。

下面我将展示页面传递字符类型参数String以及对象类型参数ObservedObjec

SwiftUI NavigationView页面之间传参数

SwiftUI NavigationView页面之间传参数

 首先定义对象Al lSearchModel


import Foundation
class AllSearchModel: ObservableObject {
    @Published var searchkey: String
    @Published var sortA: String
    @Published var sortB: String
    @Published var sortC: String
    @Published var orderBy: String
    @Published var orderType: String
    @Published var searchResultKey: String
    
    init(searchkey: String, sortA: String, sortB: String, sortC: String, orderBy: String, orderType: String,searchResultKey: String) {
        self.searchkey = searchkey
        self.sortA = sortA
        self.sortB = sortB
        self.sortC = sortC
        self.orderBy = orderBy
        self.orderType = orderType
        self.searchResultKey=searchResultKey
    }
}

页面 TestView

import SwiftUI

struct TestView: View {
    @State var viewname:String = "12345"  //定义字符串类型参数
    @ObservedObject var allsearchmodel:AllSearchModel = AllSearchModel(searchkey: "", sortA: "", sortB: "", sortC: "", orderBy: "", orderType: "",searchResultKey:"")//定义对象参数
    var body: some View {
        NavigationView{
            VStack{
                TextField("检索词", text: $allsearchmodel.searchkey)//定义输入框,值绑定对象中的属性 也可以绑定字符串
                    .border(Color.black)
                NavigationLink(destination:Test1View(viewname:viewname ,allsearchmodel:allsearchmodel)){//定义跳转页面,将要传的值放入视图定义中,多个参数,隔开
                    Text("跳转到第二个页面")
                }
            }
            
        }
    }
}

struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        TestView()
    }
}

第二个接收页面  TestView1


import SwiftUI

struct Test1View: View {
    @State var viewname:String=""
    @ObservedObject var allsearchmodel:AllSearchModel=AllSearchModel(searchkey: "", sortA: "", sortB: "", sortC: "", orderBy: "", orderType: "",searchResultKey:"")
    var body: some View {
        VStack{
            Text("参数1是:\(allsearchmodel.searchkey)")
            Text("参数2是:\(viewname)")
        }
        
    }
}

struct Test1View_Previews: PreviewProvider {
    static var previews: some View {
        Test1View()
    }
}

相关标签: SwiftUI