ViewWithTag in UICollectionViewCell returns nil in Swift (until cell is reused)
This long title is roughly my problem. I started a simple learning example using UICollectionView in a Swift project.
I added a CollectionView to a ViewController created with a template, assigned delegate and datasource. A custom cell is created in the storyboard. Reuse ID is set.
Everything is fine so far. I put one UILabel in a custom cell and gave the tag value 100.
Here's the code of my ViewController: https://gist.github.com/tomekc/becfdf6601ba64d5fd5d
And an interesting exceprt below:
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("element", forIndexPath: indexPath) as UICollectionViewCell
cell.backgroundColor = UIColor.yellowColor()
// list subviews
NSLog("--- ROW %d ---", indexPath.row)
printSubviews(cell)
if let labelka = cell.viewWithTag(100) as? UILabel {
labelka.text = String(format: "Row %d", indexPath.row)
NSLog("Found label")
}
return cell
}
func printSubviews(view:UIView) {
if let list = view.subviews as? [UIView] {
for uiv in list {
NSLog("%@ tag:%d", uiv, uiv.tag)
printSubviews(uiv)
}
}
}
The problem is that it cell.viewWithTag(100)
returns nil until the cell is reused . When I scroll through the view, so any of the cells exits the window, and reuse is forced, it viewWithTag(100)
returns the label and I can set its value.
Interestingly, I put together a similar example in Objective-C and there is no such problem. Even when building and running with XCode6 beta4.
I wonder if I missed something or is this wrong behavior?
Update: Apparently I used an overly simplistic approach. When I created my own UICollectionViewCell subclass (as I usually do), the result is correct.
source to share
No one has answered this question yet
See similar questions:
or similar: