Reputation: 479
So I am new to swift and am trying to create a custom UiCollectionView that you can horizontally scroll through, and when tapping on a button, you can add an image from your camera roll to the array of images in the collection view. This is what I have so far and I have run into some problems. I have tried watching videos online but I still get errors so i don't know what I am doing wrong. I have some images of apple products that I loaded into my assets folder and I will be using those images in an array for the collectionView. Each image will be in one colletionViewCell.
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let imageArray = [UIImage(named: "appleWatch" ), UIImage(named: "iPhone"), UIImage(named: "iPad" ), UIImage(named: "iPod" ), UIImage(named: "macBook")]
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! UICollectionViewCell
cell.ourImage?.image = self.imageArray[indexPath.row]
return cell
}
}
It gives me an error here cell.ourImage?.image = self.imageArray[indexPath.row]
and says that "value type UICollectionViewCell has no member 'ourImage'" Even though I named the outlet ourImage
on another UICollectionViewCell swift file. I have checked the Main.storyboard and I think I have named all of my classes correctly and have assigned them to the collectionViewCell and the identifier. I delete this line and it compiles fine, but whenever the app is run nothing shows up on the screen so there may be something wrong with my images too. Does anybody have any ideas? How would you go about creating a custom UiCollection View? Do I have the right idea?
Upvotes: 0
Views: 1869
Reputation: 2289
Instead of casting the dequeued cell to UICollectionViewCell
, you need to treat it as your custom UICollectionViewCell
subclass.
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourReuseIdentifier", for: indexPath) as? YourCustomCollectionViewCell {
// set the cell's custom properties
}
You can also force cast using as! YourCustomCollectionViewCell
, but I personally prefer not to do this.
Upvotes: 2