访问数组的元素并将其与单元格选定的数据相匹配

时间:2018-05-09 07:29:22

标签: ios swift

我有ResturantFile.plist,其中餐馆名称,物品和价格以形式存储 ( { 汉堡点 ( { itemName = ItemPrice = } ) } )

现在我想访问数组元素并传递给RestaunrantViewController,当我选择具有每个餐馆名称的相应名称的collectionviewcell时,在另一个viewcontroller中有一个UITableView,我想显示itemName和ItemPrice。 但我没有得到我怎么能这样做

使用此

访问ResturantFile.plist
 let pathUrl =  Bundle.main.path(forResource: "ResturantFile", ofType: ".plist")
    print("path url is",pathUrl)

    let finalArray = NSMutableArray(contentsOfFile: pathUrl!)
    print("final Array is",finalArray)

选择方法代码是:

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

    let pathUrl =  Bundle.main.path(forResource: "ResturantFile", ofType: ".plist")
    print("path url is",pathUrl)

    let finalArray = NSMutableArray(contentsOfFile: pathUrl!)
    print("final Array is",finalArray)

    let itemNames = finalArray?.sorted(by: {$0 == "ItemName"})// this is not working for me

    // pass restaurant name and image to the restaurntviewcontroller via viewcontroller
    if blockClosure != nil{ blockClosure(restaurantImageArray[indexPath.row] ,restaurantNameArray[indexPath.row] , data)
    }
}

这是我的ResturantFile.plist

2 个答案:

答案 0 :(得分:1)

在RestaurantViewController中,您需要使用所选的餐馆名称添加过滤器,例如(替换" selectedRestroName"以及来自前一个控制器的所选餐厅名称):

let pathUrl = Bundle.main.path(forResource: "ResturantFile", ofType: ".plist") print("path url is",pathUrl) 
let finalArray = NSMutableArray(contentsOfFile: pathUrl!) 
///finalArray is plish Data array, and "selectedRestroName" is the selected restaurant which is you passing from closure
    let selectedDict = finalArray.filter { (object) -> Bool in
        (object.keys).contains(where: {$0 == "selectedRestroName"})
    }.first

    let finalArraaOfSelectedRestorentData = Array(selectedDict!.values)

或者

let finalArraaOfSelectedRestorentData = selectedDict["selectedRestroName"]

答案 1 :(得分:0)

我完成了这件事

func moveToDetailController(img:UIImage,name:String)
{
    print("the rest name is", name)

    let pathUrl =  Bundle.main.path(forResource: "ResturantFile", ofType: ".plist")
    print("path url is",pathUrl as Any)

    let finalArray = NSMutableArray(contentsOfFile: pathUrl!)
    print("final Array is",finalArray)

    let restaurantNames = finalArray?.firstObject as? NSDictionary
    print("resturant name is",restaurantNames as Any)


    if let menuDataArray:[[String:Any]] = restaurantNames?.value(forKey: name) as? [[String:Any]]
    {

        print("menu data is",menuDataArray)


    let restVC = self.storyboard?.instantiateViewController(withIdentifier: "RestaurantViewController") as! RestaurantViewController

    restVC.tempImg = img
    restVC.tempTitle = name

    restVC.restMenu = menuDataArray

    self.navigationController?.pushViewController(restVC, animated: true)
    }
}

通过闭包获取之前的restName,然后匹配restName并将其放入数组,然后将数组传递给下一个控制器,然后将值放入字典并按键值分配...