Reputation: 1335
I have a ViewController with a UICollectionView where I'd like to display the first two letters of the players in the users friend list, like this:
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
contactListCollection.registerClass(PlayerCell.self, forCellWithReuseIdentifier: "PlayerCell")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PlayerCell", forIndexPath: indexPath) as! PlayerCell
let contacts = contactList.getContactList() //Array of strings
for(var i = 0; i < contacts.count; i++){
var str = contacts[i]
// First two letters
let firstTwo = Range(start: str.startIndex,
end: str.startIndex.advancedBy(2))
str = str.substringWithRange(firstTwo)
cell.setButtonTitle(str);
}
return cell;
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return contactList.getContactList().count;
}
My PlayerCell Class is as follows:
class PlayerCell : UICollectionViewCell {
@IBOutlet var button: UIButton?
func setButtonTitle(text: String){
button!.setTitle(text, forState: .Normal)
}
}
When run the code it gives: Fatal error: unexpectedly found nil while unwrapping an Optional value
I found out that the button in my PlayerCell is nil
I have added the button inside my cell in the Storyboard and Connected those with referencing outlets
Am I missing something here?
Using xCode 7 with Swift 2.0
Upvotes: 1
Views: 1087
Reputation: 2709
Try: 1. I would check that there isn't an old referencing outlet attached to the button. Right click on the button in the interface builder and ensure that only the appropriate outlet is still connected.
Ensure that in the storyboard you have set the class of the re-useable cell to PlayerCell
Ensure that you have Ctrl + dragged from the collection view to the view controller it is in and set the delegate and data source to itself.
Hopefully, one of these may help you.
Upvotes: 0
Reputation: 385988
As part of the compilation process, Xcode converts the storyboard to a collection of XIB files. One of those XIB files contains your cell design.
When your app loads the collection view controller that you designed in the storyboard, the controller takes care of registering the cell's XIB file for the cell.
You are overwriting that registration by calling registerClass(_:forCellWithReuseIdentifier:)
, severing the connection between the “PlayerCell” reuse identifier and the XIB containing the design of PlayerCell
.
Get rid of this line:
contactListCollection.registerClass(PlayerCell.self, forCellWithReuseIdentifier: "PlayerCell")
Also, make sure that in the storyboard you have set the cell's reuse identifier to "PlayerCell".
Upvotes: 1