user3255746 user3255746 - 2 months ago 20
iOS Question

Reuse Identifier on iCarousel

I am trying to build a carousel on my app based on this project, https://github.com/nicklockwood/iCarousel, only I am writing it in swift. I have it working correctly, where you can scroll through and tap on the item at index correctly here:

func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
let tempView = UIView(frame: CGRect(x: 0, y: 130, width: 295, height: 300))
let object = self.imageFilesArray.object(at: index) as! PFObject

let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0 , width: 295, height: 295)
imageView.layer.cornerRadius = 15
imageView.layer.masksToBounds = true
let imageFile = object.object(forKey: "Image") as! PFFile
imageFile.getDataInBackground{
(data, error) -> Void in
if error == nil {


}
imageView.image = UIImage(data: data!)
tempView.addSubview(imageView)
}
return tempView
}



func carousel(_ carousel: iCarousel, didSelectItemAt index: Int) {
let cell = carouselView.itemView(at: index)
let object = self.imageFilesArray[index] as! PFObject

if cell?.tag == 0 {

print("open cell")
let moveImg = CGAffineTransform(translationX: 0, y: -100)
UIView.animate(withDuration: 0.4, delay: 0.1, options: [], animations: {
//cell.imageView.transform = moveImg

}, completion: nil)
cell?.tag = 1

} else if cell?.tag == 1 {

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewController(withIdentifier: "EventDetailViewController") as! EventDetailViewController

self.present(nextViewController, animated:false, completion:nil)

}


However, what I am trying to do is when I tap the item at index, the imageView transitions on the screen. My issue is that I cannot access that particular cells imageView in order to move it. Does anyone know what I need to change?

Answer

You could give your imageView a tag like this:

let imageView = UIImageView()
imageView.frame = CGRect(x:  0, y: 0 , width: 295, height: 295)
imageView.layer.cornerRadius = 15
imageView.layer.masksToBounds = true
imageView.tag = 2

Then you can retrieve the imageView from the cell like this:

if let imageView = cell.viewWithTag(2) as? UIImageView {
    imageView.transform = moveImg
}

OR

You could filter through the subviews of the cell and find the first subview that can be cast to a UIImageView. Although this isn't very robust, consider creating a Class and XIB for this cell.

cell.subviews.flatMap { $0 as? UIImageView }.first?.transform = moveImg
Comments