Ich mache Sammlungsansicht programmatisch. Hier ist der Code in viewDidLoad funcWie erhalten Sie atIndex in UICollectionView mit swift?
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
layout.itemSize = CGSize(width: 90, height: 120)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.layer.cornerRadius = 2
collectionView!.backgroundColor = UIColor.redColor()
self.containerView.addSubview(collectionView!)
Und das sind meine Sammlung Ansicht Funktionen
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 8
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.blackColor()
cell.buttonView.addTarget(self, action: Selector("Action\(indexPath.row):"), forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
Idee, die ich auf eine Schaltfläche in der Zelle haben, und wenn ich es die Zelle drücken sollte die Farbe ändern, hier ist die Aktion Funktion
func Action0(sender: UIButton!) {
var indexPath = NSIndexPath(forRow: 0, inSection: 0)
let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
cell.backgroundColor = UIColor.blueColor()
und dies ist collectionViewCell Klasse,
class CollectionViewCell: UICollectionViewCell {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var buttonView: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
buttonView = UIButton.buttonWithType(UIButtonType.System) as! UIButton
buttonView.frame = CGRect(x: 0, y: 16, width: frame.size.width, height: frame.size.height*2/3)
contentView.addSubview(buttonView)
}
}
Der Knopf und die Aktion funktioniert, aber die Zelle Farbe ändert sich nicht, ich denke, das Problem in dieser Linie ist
let cell = collectionView!.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
Perfect! Vielen Dank! – Jeff