UITapGestureRecognizer not working in UIImageView

前端 未结 9 1636
长发绾君心
长发绾君心 2021-01-03 18:16

I had the following code:

UITapGestureRecognizer *showStoryTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showNewsStory         


        
9条回答
  •  甜味超标
    2021-01-03 19:00

    I also noticed that in swift3, if you are adding a gesture recognizer which also looks for the target and the target is usually self, then you have to make the UIView to which you are adding the gesture recognizer to be a lazy var. Otherwise the gesture recognizer won't work. I think this is a bug in swift3. Ideally if you are accessing self in a variable before the class is fully initialized, it should throw an error. The code below won't detect gesture recognizer.

    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
    }()
    

    To fix that, you have to use 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
    }()
    

提交回复
热议问题