ios 更改foreach中所选按钮项swiftui的背景色

wd2eg0qa  于 2023-05-02  发布在  iOS
关注(0)|答案(1)|浏览(119)

浏览次数:

struct SubCatProductView: View {
    
    @StateObject private var vm = SubCategoryViewModel()
    @State private var hasError = false
    
    @State private var selectedSubCat = ""
    
    var body: some View {
        
        VStack(alignment: .leading) {
            subcategory
            product
        }
        .task {
            vm.subcatRequest()
       }
    }
}

子类别视图和产品视图:
在子类别视图中显示:它不像你建议的那样工作

private extension SubCatProductView {

var subcategory: some View {
    
    ScrollView(.horizontal) {
        
        HStack {
            
            ForEach(vm.subcategories, id: \.id) { subcategory in
                Button {
                    print("selected SubCategory",subcategory.name)
                    selectedSubCat = subcategory.name
                    vm.getProducts(subcat_id: subcategory.id)
                } label: {
                    SubCatView(subcategory: subcategory)
                }
                .background((selectedSubCat == subcategory.name ? Color.yellow : Color.clear))
            }
        }
    }
    .onAppear {
        print("onAppear : ",selectedSubCat)
        if let first = vm.subcategories.first {
            print("selected Sub Cat in onTask : ",first.name)
            selectedSubCat = first.name
        }
    }
}

var product: some View {
    List {
        ForEach(vm.products, id: \.id) { product in
            ProductView(product: product)
        }
    }
}

}
视图模型:
在这个视图模型中,我有两个API调用。流程是
1.第一个API调用-〉接收数据-〉从数组中获取第0个数据,并以水平滚动视图显示数组。
1.将第0个数据作为参数传递给第二个API调用,并获取另一个数据并显示

final class SubCategoryViewModel: ObservableObject {

 @Published var subcategories : [SubData] = []
 @Published var products : [ProductData] = []
 func subcatRequest() {

     let url = "https://auroraa.site/suresh-packers/admin/api/get-sub-category-api.php"

     AF.request(url, method: .post,
                parameters: ["type": "get_sub_category","category": "1"],
                encoding: URLEncoding.default,
                headers: nil,
                interceptor: nil).response { responce in

         switch responce.result {

         case .success(let data):
             do {
                 let jsonData = try JSONDecoder().decode(SubCategory.self, from: data!)
                 print("Category Names : ",jsonData)
                 self.subcategories = jsonData.data
                 self.getProducts(subcat_id: self.subcategories[0].id)
             } catch {
                 print(error.localizedDescription)
             }
         case .failure(let error):
             print(error.localizedDescription)
         }
     }
 }

 func getProducts(subcat_id : String) {

     let productsurl = "https://auroraa.site/suresh-packers/admin/api/get-products.php"

     AF.request(productsurl, method: .post,
                parameters: ["type": "get_products","sub_category": subcat_id],
                encoding: URLEncoding.default,
                headers: nil,
                interceptor: nil).response { responce in

         switch responce.result {

         case .success(let data):
             do {
                 let jsonData = try JSONDecoder().decode(Products.self, from: data!)
                 print("Product Names : ",jsonData)
                 self.products = jsonData.data
             } catch {
                 print(error)
             }
         case .failure(let error):
             print(error)
         }
     }
 }}

我的要求是:当我打开页面的水平项目是从API和显示,但我需要使第一个项目可选择deferfault https://i.stack.imgur.com/KPKhT.jpg

deyfvvtc

deyfvvtc1#

尝试使用@State var selectionButton上的.background修饰符来实现这种方法。

struct ContentView: View {
    let arr = ["item-1","item-2","item-3","item-4"]
    @State var selection = "" // <-- here, adjust to subcategory type
    
    var body: some View {
        ScrollView(.horizontal) {
            HStack {
                ForEach(arr, id: \.self) { subcategory in
                    Button {
                        print("selected SubCategory",subcategory)
                        // vm.getProducts(subcat_id: subcategory.id)
                        selection = subcategory  // <-- here
                    } label: {
                        //  SubCatView(subcategory: subcategory)
                        Text(subcategory)
                    }
                    // --- here
                    .background((selection == subcategory ? Color.yellow : Color.clear))
                }
            }
        }
        .onAppear {
            if let first = arr.first {
                selection = first  // <-- here
            }
        }
    }
}

相关问题