Collection View Cells 不断增加,是当前数组数量的两倍
Collection View Cells are keep increasing as twice of the current array count
您好,我正在使用数据模型方法将数据加载到 collectionView
单元格中。数据获取成功,但是当我导航到另一个 viewController
并返回到当前 viewController
时,单元格的增加是当前数组计数的两倍。
我知道我使用的方法并不完美,因为我是 Swift 的新手,我是从 google 那里得到的。处理这个问题的正确方法是什么?
API 通话
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
Collectionview 代表
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCoachCCell", for: indexPath)
as! MyCoachCCell
// cell.activitiesImg.image = collectionViewImageArray[indexPath.row]
let mCategories = categories[indexPath.row]
cell.className.text = mCategories.title
// cell.classThumb.image = collectionViewImageArray[indexPath.row]
// fetching image
let mcImageURL = mCategories.imageURL
Alamofire.request(mcImageURL).responseData(completionHandler: { response in
// debugPrint(response)
// debugPrint(response.result)
if let image1 = response.result.value {
self.imagefinal = UIImage(data: image1)!
cell.classThumb.image = self.imagefinal
print("IMG", self.imagefinal! )
}
})
return cell
}
请在追加到数组之前编写代码。
self.categories.removeAll()
在你的函数中,在 for 循环开始之前添加这一行。
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories.removeAll()
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
您已经在 viewWillAppear method.So 中调用了网络服务,每当您从另一个视图控制器返回时,它都会将数据附加到相同的现有 array.So,编写上面的代码将从数组中删除现有数据.
或者您可以做的其他事情是在 viewDidLoad 方法中调用网络服务。
希望对您有所帮助。
用这个替换你的函数。
您需要在追加之前从数组类别中删除所有元素。
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories = []
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
您好,我正在使用数据模型方法将数据加载到 collectionView
单元格中。数据获取成功,但是当我导航到另一个 viewController
并返回到当前 viewController
时,单元格的增加是当前数组计数的两倍。
我知道我使用的方法并不完美,因为我是 Swift 的新手,我是从 google 那里得到的。处理这个问题的正确方法是什么?
API 通话
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
Collectionview 代表
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCoachCCell", for: indexPath)
as! MyCoachCCell
// cell.activitiesImg.image = collectionViewImageArray[indexPath.row]
let mCategories = categories[indexPath.row]
cell.className.text = mCategories.title
// cell.classThumb.image = collectionViewImageArray[indexPath.row]
// fetching image
let mcImageURL = mCategories.imageURL
Alamofire.request(mcImageURL).responseData(completionHandler: { response in
// debugPrint(response)
// debugPrint(response.result)
if let image1 = response.result.value {
self.imagefinal = UIImage(data: image1)!
cell.classThumb.image = self.imagefinal
print("IMG", self.imagefinal! )
}
})
return cell
}
请在追加到数组之前编写代码。
self.categories.removeAll()
在你的函数中,在 for 循环开始之前添加这一行。
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories.removeAll()
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
您已经在 viewWillAppear method.So 中调用了网络服务,每当您从另一个视图控制器返回时,它都会将数据附加到相同的现有 array.So,编写上面的代码将从数组中删除现有数据.
或者您可以做的其他事情是在 viewDidLoad 方法中调用网络服务。
希望对您有所帮助。
用这个替换你的函数。
您需要在追加之前从数组类别中删除所有元素。
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories = []
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}