Search code examples
iosuitableviewuiscrollviewswift2uipagecontrol

add UIPagerControl inside a UITableViewCell's imageView


inside my tableView's Cell i have a ImageView and there i wanna insert a UIPageControll so that i can add multiple images in my ImageView and scroll through it like this :

enter image description here

this is what i tried (and got stuck ) :

tableViewCell:

class EventsTableViewCell: UITableViewCell {
     @IBOutlet var coverView: UIView!
    @IBOutlet var pageController: UIPageControl!
    @IBOutlet var imgView: UIImageView!

    let swipeGestureLeft = UISwipeGestureRecognizer()
    let swipeGestureRight = UISwipeGestureRecognizer()
...................... ........... 
...........
}

TableView:

 ///// inside cellforRowAtIndexPath

........

    PagerController = cell.pageController
    swipeGestureLeft = cell.swipeGestureLeft
    swipeGestureRight = cell.swipeGestureRight
    coverView = cell.coverView

    // set gesture direction
    self.swipeGestureLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.swipeGestureRight.direction = UISwipeGestureRecognizerDirection.Right
    // add gesture in to view

    coverView.addGestureRecognizer(self.swipeGestureLeft)
    coverView.addGestureRecognizer(self.swipeGestureRight)

    // add gesture target
    self.swipeGestureLeft.addTarget(self, action: #selector(self.handleSwipeLeft(_:)))
    self.swipeGestureRight.addTarget(self, action: #selector(self.handleSwipeRight(_:)))

.
.
.
.
.
.

    // functions for recognising the Gestures
func handleSwipeLeft(gesture: UISwipeGestureRecognizer){
    if self.PagerController.currentPage != 2 {

          print("left :\(self.PagerController.currentPage) ")

        self.PagerController.currentPage += 1


        imgView.image = UIImage(named: "cover\(self.PagerController.currentPage)")
    }
}

// 
func handleSwipeRight(gesture: UISwipeGestureRecognizer){

    if self.PagerController.currentPage != 0 {

        print("right  :\(self.PagerController.currentPage)")

        imgView.image = UIImage(named: "cover\(self.PagerController.currentPage)")

        self.PagerController.currentPage -= 1
    }


}

you can see that am able to recognise the gesture over my coverView which is an UIView covering the ImageView and am also able to call this functions but now how am gonna change the image ?? any clue or guidance will be so helpful for me

P.s if my question is not clear enough then please let me know i'll add some details


Solution

  • On your cellForRowAt index add this code

    cell.imgView.userInteractionEnable = true
    cell.imgView.addGestureRecognizer(self.swipeGestureLeft)
    cell.imgView.addGestureRecognizer(self.swipeGestureRight)
    

    Hope this will help you.