简体   繁体   English

UiCollectionView单元格选择错误

[英]UiCollectionView Cell Selection Error

I have used Alamofire and SwiftyJSON To Populate the UiCollectionview and its working fine but didSelectItemAtIndexPath function shows array out of index thought I have printed the array count and it's not empty 我已经使用Alamofire和SwiftyJSON来填充UiCollectionview及其工作正常,但didSelectItemAtIndexPath函数显示数组超出索引,以为我已经打印了数组计数并且它不为空

any suggestion 任何建议

here is my code:- 这是我的代码:-

The model 该模型

import Foundation

class ProductModel {
private var _ProductItemId: String!
private var _ProductMainCategory: String!
private var _ProductCategoryId: String!
private var _ProductName: String!
private var _ProductItemNo: String!
private var _ProductAvalaibility: String!
private var _ProductSeoDesc: String!
private var _ProductImageURL: String!
private var _ProductBrand_ID: String!
private var _ProductCat_name: String!

//Level 1
private var _ProductTotalQuantity : String!
private var _Productprice : String!
private var _ProductSalePrice : String!
private var _ProductWeightName : String!
private var _ProductCode : String!




var ProductItemId : String {
    return _ProductItemId
}

var ProductMainCategory : String {
    return _ProductMainCategory
}

var ProductCategoryId : String {
    return _ProductCategoryId
}

var ProductName : String {
    return _ProductName
}

var ProductItemNo : String {
    return _ProductItemNo
}

var ProductAvalaibility : String {
    return _ProductAvalaibility
}

var ProductSeoDesc : String {
    return _ProductSeoDesc
}

var ProductImageURL : String {
    return _ProductImageURL
}

var ProductBrand_ID: String {
    return _ProductBrand_ID
}

var ProductCat_name: String {
    return _ProductCat_name
}

//Level 1
var ProductTotalQuantity : String {
    return _ProductTotalQuantity
}

var Productprice : String {
    return _Productprice
}

var ProductSalePrice : String {
    return _ProductSalePrice
}

var ProductWeightName : String {
    return _ProductWeightName
}

var ProductCode : String {
    return _ProductCode
}



//Initilizer
init(ProductImageURL : String, ProductName : String, Productprice : String, ProductSalePrice : String)
{

    self._ProductName = ProductName
    self._ProductImageURL = ProductImageURL//

    //Level 1
    self._Productprice = Productprice//
    self._ProductSalePrice = ProductSalePrice//

}

My CollectionView Delegates and Data sources 我的CollectionView委托和数据源

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ProductCell", forIndexPath: indexPath)as? ProductCell {

        let _prod: ProductModel!
            _prod = prod [indexPath.row]
        cell.configureCell(_prod)
        return cell
    }
    else{
        return UICollectionViewCell()
    }


}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let prodDetail: ProductModel!
    prodDetail = prod[indexPath.row] //error Array index out of range 
    print(prodDetail.Productprice)
    performSegueWithIdentifier("productDetailSegue", sender: prodDetail)

}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //if inSearchMode{
        //return filteredProd.count
  //  }
    return prod.count
}

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1
}

Calling API and Parsing 调用API和解析

    Alamofire.request(.POST, "http://www.picknget.com/webservice/index.php/Home/filter_grocery_product_practice/", parameters: parameterDictionary as? [String : AnyObject])
        .responseJSON { response in
            if let value = response.result.value {
                let json = JSON(value)
                print(json)
                if let _statusCode = json["status"].string {
                    // print("the ststus code is ", _statusCode)
                    if (_statusCode == "1"){
                        self.parseJSON(json)
                    }
                    if (_statusCode == "0"){
                        SwiftSpinner.hide({
                            self.callAlert("OOP's", _msg: "No More Product is available in this section right now")
                        })
                    }
                }
                //print ("json result ", json)

            }
        }.responseString { response in
            //print("response ",response.result.value)
    }
}

func parseJSON(json: JSON) {
    for result in json["cat"].arrayValue {
        let name = result["Name"]

        let aString: String = "\(result["ImageURL"])"
        let product_Image_Url  = aString.stringByReplacingOccurrencesOfString("~", withString: "http://www.picknget.com", options: NSStringCompareOptions.LiteralSearch, range: nil)
        let price = result["cat_price"][0]["Price"].string
        let SalePrice = result["cat_price"][0]["SalePrice"].string


        let product = ProductModel(ProductImageURL: "\(product_Image_Url)", ProductName: "\(name)", Productprice: "\(price!)", ProductSalePrice: "\(SalePrice!)")
        prod.append(product)
    }

    print("@@@@@@@@")
    print(prod.count)
    dispatch_async(dispatch_get_main_queue(),{
        self.productCollect.reloadData()
    });
}

According your comments, I believe the issue is related to how you set the obtained Products for the Collection View. 根据您的评论,我认为问题与您如何为“收藏夹视图”设置获得的产品有关。

It's very likely that the function parseJSON executes on a secondary thread. 函数parseJSON很可能在辅助线程上执行。 This is actually, the same execution context of the completion handler of method responseJSON . 实际上,这与方法responseJSON的完成处理程序的执行上下文相同。

Within function parseJSON you have this statement: 在函数parseJSON您具有以下语句:

    prod.append(product)

Here, prod should not be a global variable or not a member variable of the view controller! 在这里, prod 应该是一个全局变量或视图控制器的一个成员变量! Make it a local variable in function parseJSON ! 在函数parseJSON使其成为局部变量!

Your view controller should have a property of this array as well, eg products . 您的视图控制器也应具有此数组的属性,例如products This serves as the "model" of the view controller. 这充当视图控制器的“模型”。 It will be accesses only from the main thread. 只能从主线程进行访问。

In parseJSON assign the view controller the products as follows: parseJSON为视图控制器分配以下产品:

func parseJSON(json: JSON) {
    var tmpProducts: [Product] = []
    for result in json["cat"].arrayValue {
        let name = result["Name"]

        let aString: String = "\(result["ImageURL"])"
        let product_Image_Url  = aString.stringByReplacingOccurrencesOfString("~", withString: "http://www.picknget.com", options: NSStringCompareOptions.LiteralSearch, range: nil)
        let price = result["cat_price"][0]["Price"].string
        let SalePrice = result["cat_price"][0]["SalePrice"].string


        let product = ProductModel(ProductImageURL: "\(product_Image_Url)", ProductName: "\(name)", Productprice: "\(price!)", ProductSalePrice: "\(SalePrice!)")
        tmpProducts.append(product)
    }

    dispatch_async(dispatch_get_main_queue(),{
        self.products = tmpProducts   // assuming `self` is the ViewController
        self.productCollect.reloadData()
    });
}

Note: you need to change your Data Source Delegates accordingly, eg accessing the "model" ( self.products.count ) etc. 注意:您需要相应地更改数据源代理,例如,访问“模型”( self.products.count )等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM