簡體   English   中英

UiCollectionView單元格選擇錯誤

[英]UiCollectionView Cell Selection Error

我已經使用Alamofire和SwiftyJSON來填充UiCollectionview及其工作正常,但didSelectItemAtIndexPath函數顯示數組超出索引,以為我已經打印了數組計數並且它不為空

任何建議

這是我的代碼:-

該模型

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//

}

我的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
}

調用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()
    });
}

根據您的評論,我認為問題與您如何為“收藏夾視圖”設置獲得的產品有關。

函數parseJSON很可能在輔助線程上執行。 實際上,這與方法responseJSON的完成處理程序的執行上下文相同。

在函數parseJSON您具有以下語句:

    prod.append(product)

在這里, prod 應該是一個全局變量或視圖控制器的一個成員變量! 在函數parseJSON使其成為局部變量!

您的視圖控制器也應具有此數組的屬性,例如products 這充當視圖控制器的“模型”。 只能從主線程進行訪問。

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()
    });
}

注意:您需要相應地更改數據源代理,例如,訪問“模型”( self.products.count )等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM