1

I have a UICollectionViewCell that currently takes up the entire view of a (parent) UICollectionViewController; that is, there is 1 section and 1 cellatindex.

I also have a textfield within this UICollectionViewCell, as a subview, along with a number of other subviews.

I would like to enable user to click outside of the textfield and scroll to the top of the cell.

I am currently including IQKeyboardManagerSwift as a cocoa-pod, which causes the textfield to pop-up to the top of the screen when the keyboard appears. Currently when a tap is recognized (which I have implemented through handleViewTap(sender: UITapGestureRecognizer)), I dismiss the keyboard and the entire cell scrolls down by the keyboard height, bringing the entire cell down with it. I would like to reset the cell so that it is pushed up to the top of the view.

Screen-shots as follows:

Initial load

enter image description here

Clicking on the textfield (keyboard appears and pushes collectionview upwards thanks to IQKeyboardManagerSwift [note: this functionality actually fails on the first click inside the textfield however])

enter image description here

Tapping outside the textfield pushes the entire cell to the center of the screen:

enter image description here

I would like to have the cell scroll back to the top of the cell, i.e. reset to the initial image view, or the initial load (first picture). I have tried the following inside the tap function, but it does not work:

let visibleItems: NSArray = self.collectionView!.indexPathsForVisibleItems as NSArray
let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath
let nextItem: IndexPath = IndexPath(item: currentItem.item + 0, section: 0)
self.collectionView?.scrollToItem(at: nextItem, at: .top, animated: true)

Additionally: The first time the textfield is tapped, the textfield is pushed off-screen, above the current view top. (below) I think if I can scroll inside the UICollectionViewCell itself somehow, all these issues would be fixed. However, I am not sure how to scroll within a uicollectionviewcell itself, only how to scroll to certain cell inside a uicollectionview.

enter image description here

Jeeves
  • 424
  • 1
  • 7
  • 25

1 Answers1

0

To change the positioning of the cell use: collectionView.setContentOffset(CGPoint(x: x, y: 0), animated: true) and change the x value of the point depending on how much you want it to be moved.

Nick Marinov
  • 128
  • 1
  • 10
  • this lead me to: self.collectionView?.contentOffset = CGPoint(x: -((self.collectionView?.contentInset.left)!), y: -((self.collectionView?.contentInset.top)!)) -- which is the line I was looking for, found at: http://stackoverflow.com/a/33435087/4314265 – Jeeves May 22 '17 at 05:35