0

I want to resize the collection cell by dragging its edge. What is the best possible way? Currently, I am changing the current cell width manually. but it disrupts other cells and if I invalidate layout or reloadcollection() then it cause huge memory. Please suggest some best ways to get this functionality. I am attaching the video of the functionality please check.

Resizing Example

I have tried to do it by invalidateLayout every time or reload cell it cost me huge cpu usage and memory. Please suggest some better idea.

Avijit Mondal
  • 59
  • 1
  • 9

1 Answers1

1

Add a UIPanGestureRecognizer to each collection view cell: In your custom collection view cell class, add the pan gesture recognizer in the initialization method or awakeFromNib method.

class CustomCollectionViewCell: UICollectionViewCell {
var panGestureRecognizer: UIPanGestureRecognizer!

override func awakeFromNib() {
    super.awakeFromNib()

    panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
    self.contentView.addGestureRecognizer(panGestureRecognizer)
}

@objc func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
    // Handle resizing logic here
}}

Implement the resizing logic: When the pan gesture is recognized, you need to calculate the new width of the cell and adjust its frame accordingly. Additionally, you may need to update the layout of other cells to accommodate the resized cell.

@objc func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
if recognizer.state == .changed {
    let translation = recognizer.translation(in: self.contentView)
    let newWidth = self.contentView.frame.width + translation.x

    // Limit the minimum and maximum width of the cell
    let minimumWidth: CGFloat = 50.0 // Set your desired minimum width
    let maximumWidth: CGFloat = 200.0 // Set your desired maximum width


    let clampedWidth = min(maximumWidth, max(minimumWidth, newWidth))
    let widthDiff = clampedWidth - self.contentView.frame.width

    // Resize the current cell
    self.contentView.frame.size.width += widthDiff

    // Notify the collection view to update its layout
    if let collectionView = self.superview as? UICollectionView {
        collectionView.collectionViewLayout.invalidateLayout()
    }
}}