简体   繁体   中英

Pinch to Zoom a UIImageView in CollectionView Cell

I'm trying to add an IBAction to pinch and zoom an image to a custom cell class, but storyboard gives an error that actions cannot be targeted at repeating content. Here is the custom cell class:

class PhotoCell: UICollectionViewCell {

// Outlets
@IBOutlet weak var photoImgV: UIImageView!
@IBOutlet weak var captionTV: UITextView!
@IBOutlet weak var captionBtn: UIButton!
@IBOutlet weak var captionStackView: UIStackView!
@IBOutlet weak var likeCountLabel: UILabel!
@IBOutlet weak var comntCountLabel: UILabel!
@IBOutlet weak var pinch: UIPinchGestureRecognizer!

// Actions
@IBAction func pinch(sender:UIPinchGestureRecognizer) {
    if sender.state == .began || sender.state == .changed {
        let currentScale = self.photoImgV.frame.size.width / self.photoImgV.bounds.size.width
        let newScale = currentScale*sender.scale
        let transform = CGAffineTransform(scaleX: newScale, y: newScale)
        self.photoImgV.transform = transform
        sender.scale = 1
    }
}

@IBAction func showCaption(){
    UIView.animate(withDuration: 0.5) {
        if self.captionStackView.arrangedSubviews[1].isHidden {
            self.captionStackView.arrangedSubviews[1].isHidden = false
        }else{
            self.captionStackView.arrangedSubviews[1].isHidden = true
        }
    }
}

It allowed me to connect an IBAction to a button to show/hide caption in the same cell, so why pinch isn't allowed? How would I pinch and zoom an image in a cell?

I solved it by deleting the pinch gesture from storyboard and creating it in the awakeFromNib() method:

    override func awakeFromNib() {
    super.awakeFromNib()
    let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.pinch(sender:)))
     photoImgV.addGestureRecognizer(pinch)
}

everything else is the same.

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