Maysam
Maysam

Reputation: 7367

Having multiple instances of a subclass in Swift

I've subclassed a UICollectionViewCell in which there is a UIImageView. This image view is connected to an image view control on the story board. This is the subclass:

class ProfilesCell: UICollectionViewCell {
    @IBOutlet weak var ProfileImage: UIImageView!

    func setCell(item:Profile) {
        ProfileImage.image = UIImage(named: item.profileThumb)
        ProfileImage.layer.borderWidth = 0.5
        ProfileImage.layer.borderColor = UIColor.grayColor().CGColor
    }
}

I've created an instance of it and it works fine, but what about another instance? how can I choose it as a custom class for another UICollectionViewCell without reconnecting the ProfileImage to another control?

Or shall I connect that IBOutlet to the UIImageView at the first place?

Storyboard: enter image description here

Upvotes: 0

Views: 164

Answers (2)

bolnad
bolnad

Reputation: 4583

If you want to use a UICollectionViewCell across multiple UICollectionView, you should create the UICollectionViewCell in a separate .xib. In this case you will have ProfileCell.xib, and ProfileCell.swift. In the .xib file you drag an instance of a UICollectionViewCell onto the screen and set it up the way you would as a prototype cell on a CollectionView.

UICollectionViewCell on xib

Then you will need to register the cell with your collectionview.

    //set this up in viewDidLoad
    let nib = UINib(nibName: "ProfileCell", bundle: nil)
    self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "ProfileCell")

Then in cellForItemAtIndexPath just reference the cell in the normal way

 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    cell =    self.collectionView?.dequeueReusableCellWithReuseIdentifier("ProfileCell, forIndexPath: indexPath) as! ProfileCell
    cell.setCell()
    return cell
 }

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

This image view [from the cell] is connected to an image view control on the story board.

I assume that you are talking about a UICollectionViewCell prototype. In this case, the object that you manipulate in the story board is not the collection view cell, it's a prototype of all image view cells in your UIImageView.

I've created an instance of it and it works fine, but what about another instance?

This is precisely the scenario the designers of Swift had in mind, so everything should work the way you expect. When you call dequeueReusableCellWithReuseIdentifier: method, Cocoa instantiates the cell for you, "wires up" your ProfileImage to its UIImageView outlet, and gives you a cell that is ready for use.

Upvotes: 1

Related Questions