问题
I'm looking to retrieve data, such as a label.text from within a visible cell, and I don't know how that would be possible.
Plain context: I have a collectionView displaying questions (each cell display a question) the collectionView is within a UIView.
Within this same uiview I have a button which, when pressed, should validate the question answer. At this point the only thing Im doing is linking a @IBAction to the button in order for it to println the question from the visible cell (only one cell is visible).
here is how I construct the cell
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// return arr.count
return questionData.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:CollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
let thereq:PFObject = self.questionData.objectAtIndex(indexPath.row) as PFObject
// cell.contentView.frame = cell.bounds
var action = thereq.objectForKey("action") as String
var what = thereq.objectForKey("what") as String
cell.askingQuestionLabel.text = "where \(action) \(what)"
return cell
}
on button touch (button is out of the cell).
I know visibleCells()
exists but it doesn't look like I can retrieve info out of it.
for cell in self.collectionView!.visibleCells() as [UICollectionViewCell] {
}
Is there any way?
回答1:
You already have a custom collection view cell class. The obvious solution is to pass the PFObject to the CollectionViewCell in your cellForItemAtIndexRow method, and then retrieve it from the cell when the button is clicked.
Just cast the return value from visibleCells to your collection view cell class and then pull the PFObject out of it.
回答2:
To access data (such as a label.text) within a visible cell, you can use the visibleCells() method as follow:
for item in self.collectionView!.visibleCells() as [UICollectionViewCell] {
var indexpath : NSIndexPath = self.collectionView!.indexPathForCell(item as CollectionViewCell)!
var cell : CollectionViewCell = self.collectionView!.cellForItemAtIndexPath(indexpath) as CollectionViewCell
//access cell data
println(cell.labelName.text)
}
来源:https://stackoverflow.com/questions/26820397/is-it-possible-to-retrieve-data-from-collectionviewcell