简体   繁体   中英

UICollectionViewCell Scrolling : Swift 3

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

在此输入图像描述

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])

在此输入图像描述

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

在此输入图像描述

I would like to have the cell scroll back to the top of the cell, ie 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.

在此输入图像描述

要更改单元格的定位,请使用: collectionView.setContentOffset(CGPoint(x: x, y: 0), animated: true)并根据您希望移动多少来更改点的x值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM