Home > AI > IOS > SwiftUI >

@Binding

Example 1: The view to use @Binding can modify it, which means @Binding variable is get and set enabled.

import SwiftUI

struct BView: View {
    @State var show: Bool = false
    
    var body: some View {
        DView(show: $show)
    }
}



struct DView: View {
    @Binding var show: Bool
    
    var body: some View {
        Group {
            if show {
                Image(systemName: "pencil")
                    
            } else {
                
                Text("Hello, World!")
            }
        }.onAppear{
            show = true
        }
    }
}

Example 2: @Binding pass variable

NavLeftView.swift

struct NavLeftView: View {
    @State var index: Int = 0
    
    var body: some View {
        HStack {
            NavLeftUnitView(des: "综合", id: 0, index: $index)
            NavLeftUnitView(des: "最新", id: 1, index: $index)
        }
    }
}

NavLeftUnitView.swift

struct NavLeftUnitView: View {
    var index: Binding<Int>
    
    var des: String = ""
    var id: Int = 0
    
    init(des: String, id: Int, index: Binding<Int>) {
        self.des = des
        self.id = id
        self.index = index
    }
  
    
    var body: some View {
        Text(self.des)
            .foregroundColor(self.index.wrappedValue == self.id ? .blue : .black)
            .font(self.index.wrappedValue == self.id ? .title2 : .headline)
            .onTapGesture {
                self.index.wrappedValue = self.id
            }
    }
}

Leave a Reply