无法解释的点击手势行为

时间:2018-09-20 23:46:17

标签: swift xcode uigesturerecognizer

我遇到两种我无法解释的奇怪的轻击手势行为。首先输入代码:

import Foundation

class Popover:NSObject {

private var image:UIImage!

private lazy var toastImageView:UIImageView = {
    let imageView = UIImageView()
    imageView.image = self.image!
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
    imageView.addGestureRecognizer(tap)

    return imageView
}()

private lazy var dimView:UIView = {
    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.black.withAlphaComponent(0.66)
    view.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
    view.addGestureRecognizer(tap)

    return view
}()

func createToastWith(image:UIImage, onParent parentView:UIView, relativeToView:UIView) {

    self.image = image

    parentView.addSubview(dimView)
    parentView.addSubview(toastImageView)

    dimView.leftAnchor.constraint(equalTo: parentView.leftAnchor, constant: 0).isActive = true
    dimView.rightAnchor.constraint(equalTo: parentView.rightAnchor, constant: 0).isActive = true
    dimView.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 0).isActive = true
    dimView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor, constant: 0).isActive = true

    toastImageView.leadingAnchor.constraint(equalTo: relativeToView.leadingAnchor, constant: 4).isActive = true
    toastImageView.bottomAnchor.constraint(equalTo: relativeToView.bottomAnchor, constant: -10).isActive = true
    toastImageView.trailingAnchor.constraint(equalTo: relativeToView.trailingAnchor, constant: -40).isActive = true

    UIView.animate(withDuration: 2.0, delay: 4.0, options: .curveLinear , animations: {
        self.toastImageView.alpha = 0.0
    }, completion: {(isCompleted) in
        self.dimView.removeFromSuperview()
        self.toastImageView.removeFromSuperview()
    })
}

@objc private func viewTapped() {
    print("TAPPED!")
    self.toastImageView.layer.removeAllAnimations()
}

}

问题1:toastImageView的敲击手势未得到确认。

问题#2:虽然dimView的敲击手势已被确认,但只有在UIView.animate块处于播放状态时,该手势才有效。如果我删除了该块(作为测试),则dimView的点击手势也不起作用。

所以问题是,为什么点击手势不适用于toastImageView,为什么动画块必须存在才能使其与dimView一起使用?当我说它不起作用时,是指未调用viewTapped函数。

通过viewDidDisplay函数中的VC调用此类。我也尝试过setNeedsDisplaysetNeedLayout无效。

更新1:似乎toastImageView的问题是Alpha。我知道您无法轻按隐藏的视图,但是我想这会在隐藏过程中扩展到视图。因此,即使过渡到alpha 0,它也不起作用。因此,这回答了问题1。但是,就动画块的要求而言,它无法回答问题2。

更新2:之前,我认为我检查了变暗的视图,以防止从StrongWeak的位置调用它。我没有并且只检查了我们现在知道的图像视图,它是由alpha过渡引起的。因此,正如Sh_Khan指出的那样,解决第二个问题的方法是该类的弱点。

总的来说,虽然我了解了Apple为什么不允许触摸被隐藏的项目(通过alpha或其他方式),但是在处理隐藏属性(alpha)处于过渡状态的动画时,这有些破损。仍然允许点击直到从屏幕上消失之前,这将非常有帮助。

0 个答案:

没有答案