從HERE我拿了一個示例項目收集視圖,我做了一些修改,根據您的要求。
下面是用於在用戶按下視圖上的按鈕時更新集合數組的完整代碼。
import UIKit
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, CustomCollectionViewCellDelegate {
@IBOutlet weak var overlayView: UIView!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var overlayLabel: UILabel!
var purchaseCount:Float = 0.0
//Your collection view data source at start.
var cellArray = ["Cell 1", "Cell 2", "Cell 3", "Cell 4"]
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 50, left: 25, bottom: 50, right: 25)
layout.itemSize = CGSize(width: 100, height: 100)
collectionView!.collectionViewLayout = layout
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.backgroundColor = UIColor.blackColor()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.blackColor()
cell.textLabel?.text = cellArray[indexPath.row]
cell.imageView?.image = UIImage(named: "circle")
cell.imageViewStar?.image = UIImage(named: "star")
cell.delegate = self
return cell
}
//action when user press button into view
@IBAction func addNewCell(sender: AnyObject) {
//Insert an element into your collection array.
cellArray.insert("New Cell 1", atIndex: 2)
cellArray.insert("New Cell 2", atIndex: 3)
//reload your collection view.
self.collectionView.reloadData()
}
// MARK: CustomCollectionViewCellDelegate
func starImageHit(price:Float) {
print("star image hit in view controller")
self.purchaseCount = self.purchaseCount + price
self.overlayView.hidden = false
self.overlayView.alpha = 1.0
self.overlayLabel.text = "\(self.purchaseCount)"
UIView.animateWithDuration(1.0, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.overlayView.alpha = 0.0
self.view.layoutIfNeeded()
}, completion: nil)
}
}
,你會得到結果:
而且HERE是示例項目適合你。
也許你可以更新你的數組,然後更新集合視圖。 –
更新你的UICollectionView的dataSource。 – Larme
任何代碼的幫助,如果你不介意嗎?我的意思是如果你有一些時間。 –