我还注意到,在 swift3 中,如果您要添加一个手势识别器,该手势识别器也会查找目标并且目标通常是self
,那么您必须将要添加手势识别器的 UIView 设置为lazy var
. 否则手势识别器将无法工作。我认为这是swift3中的一个错误。理想情况下,如果您在类完全初始化之前访问变量中的 self,它应该会引发错误。下面的代码不会检测手势识别器。
let messageImageView: CachedImageView = {
let iv = CachedImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.layer.cornerRadius = 16
iv.layer.masksToBounds = true
iv.contentMode = .scaleAspectFill
iv.isUserInteractionEnabled = true
let zoomTap = UITapGestureRecognizer(target: self, action: #selector(handleZoomTap))
zoomTap.numberOfTapsRequired = 1
iv.addGestureRecognizer(zoomTap)
return iv
}()
要解决这个问题,你必须使用lazy var
lazy var messageImageView: CachedImageView = {
let iv = CachedImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.layer.cornerRadius = 16
iv.layer.masksToBounds = true
iv.contentMode = .scaleAspectFill
iv.isUserInteractionEnabled = true
let zoomTap = UITapGestureRecognizer(target: self, action: #selector(handleZoomTap))
zoomTap.numberOfTapsRequired = 1
iv.addGestureRecognizer(zoomTap)
return iv
}()