UIPickerView取决于第一个组件

时间:2017-12-03 19:20:07

标签: ios swift core-data uipickerview

所以我有一个带有两个组件的UIPickerView。第一个叫做“橱柜”,第二个叫“抽屉”。他们在CoreData Cupboards中具有一对多的关系< - >>抽屉。我想如果我选择一个橱柜,只会显示匹配的抽屉。我不确定如何处理这种关系。

这就是我展示橱柜的原因:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if(component==0){
                return cupboards.count
            }

     xxxx

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if(component==0){
        return cupboards[row].name
    }

    xxxx

}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if(component==0){

    }
}

提前谢谢

更新

现在就这样了,但我没有结果。

var cupboardDrawers = [Drawer]()

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if(component==0){
        let request: NSFetchRequest<Drawer> = Drawer.fetchRequest()
        request.predicate = NSPredicate(format: "cupboard == %@", cupboards[row].name!)

        do{
            let result = try mgdContext.fetch(request)
            cupboardDrawers = result
            addEatDataPicker.reloadAllComponents()
        }catch{
            print(error.localizedDescription)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用提取结果创建和更新cupboardDrawers数组:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 2
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    if(component==0){
        return cupboards.count
    } else { 
        return cupboardDrawers.count
    }
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    if(component==0){
        return cupboards[row].name
    } else {
        return cupboardDrawers[row].yourProperty
    }
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if(component==0){
        // you can add this part to a separate function and call it here
        cupboardDrawers = []
        let request = NSFetchRequest<Drawer>(entityName:”Drawer”)
        request.predicate = YourPredicate with cupboards[row].name
        do {
            let items = context.fetch(request)
            guard items.count > 0 else {
                 print(“no items found”)
                 return 
            }
            cupboardDrawers = items
            //reload your picker
        } catch { 
              print(error) 
        }
    }
}