【问题标题】:My UITapGestureRecognizer affects all elements in TableViewCell我的 UITapGestureRecognizer 影响 TableViewCell 中的所有元素
【发布时间】:2021-07-16 08:46:08
【问题描述】:

我正在尝试做我的第一个应用程序,我需要添加 UITapGestureRecognizer 来缩放 TableViewCell 中的照片。

它有效,但不正确——我的手势不仅缩放 ViewCell 中的照片,还缩放 ViewCell 中的所有元素。我该如何解决这个问题?

我所有的 TableViewCell 代码:

import UIKit

class PhotosCollectionViewCell: UICollectionViewCell {
    
    static let identifier = "PhotosCollectionViewCell"
    
    @IBOutlet weak var mainPhoto: UIImageView!
    @IBOutlet weak var mainLabel: UILabel!
    
    var isInScale: Bool = false
        
    func configure(photo: PhotosInProfile) {
        mainPhoto.image = UIImage(named: photo.mainPhoto)
        mainLabel.text = "Date: \(photo.date)"
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(imageDoubleTapped))
        doubleTap.numberOfTapsRequired = 2
        mainPhoto.isUserInteractionEnabled = true
        mainPhoto.addGestureRecognizer(doubleTap)
    }
    
    @objc func imageDoubleTapped() {
        if isInScale {
            self.transform = .identity
        } else {
            self.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
        }
        isInScale.toggle()
    }
}

【问题讨论】:

  • 当您执行self.transform 时,self 是一个PhotosCollectionViewCell 实例。你指的是mainPhoto.transform 吗?
  • @Larme 哦,你是对的。我在这里将self 更改为mainPhoto 并且有效。谢谢!

标签: ios swift iphone xcode uigesturerecognizer


【解决方案1】:

导入 UIKit

类 PhotosCollectionViewCell: UICollectionViewCell {

static let identifier = "PhotosCollectionViewCell"

@IBOutlet weak var mainPhoto: UIImageView!
@IBOutlet weak var mainLabel: UILabel!

var isInScale: Bool = false
    
func configure(photo: PhotosInProfile) {
    mainPhoto.image = UIImage(named: photo.mainPhoto)
    mainLabel.text = "Date: \(photo.date)"
}

override func awakeFromNib() {
    super.awakeFromNib()
    let doubleTap = UITapGestureRecognizer(target: self, action: #selector(imageDoubleTapped))
    doubleTap.numberOfTapsRequired = 2
    mainPhoto.isUserInteractionEnabled = true
    mainPhoto.addGestureRecognizer(doubleTap)
}

@objc func imageDoubleTapped() {
    if isInScale {
        mainPhoto.transform = .identity
    } else {
        mainPhoto.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
    }
    isInScale.toggle()
}

}

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2019-06-01
    相关资源
    最近更新 更多