Swift:Gesture Recognizer在将alpha更改为0并返回1

时间:2017-12-05 18:53:45

标签: ios swift uiview uitapgesturerecognizer

有问题的UIViewheaderView

    if isShown {
        stack.alpha = 1.0
        self.isStackShown = true
        DispatchQueue.main.async {
            self.headerView.isHidden = !isShown
            self.stack.addArrangedSubview(self.headerView)

            // add touch gesture recognizer to stack view header
            let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
            self.headerView.addGestureRecognizer(tapFind)
        }
    } else {
        stack.alpha = 0.0
        self.isStackShown = false
        DispatchQueue.main.async {
            self.headerView.isHidden = isShown
            self.stack.removeArrangedSubview(self.headerView)
        }
    }

点按手势识别器未注册任何水龙头
self.stack是包含headerView的堆栈视图 显示或隐藏headerView的条件正在以不同的方法处理,只是将布尔self.isStackShown传递给此方法以相应地显示/隐藏。

2 个答案:

答案 0 :(得分:1)

您正在使用UIGestureRecognizerUIGestureRecognizer是一个多态基类,应该真正是子类。 UITapGestureRecognizer是处理水龙头的具体子类。改为使用它。

let tapFind = UITapGestureRecognizer(target: self, action: #selector(self.handleFindTap))
self.headerView.addGestureRecognizer(tapFind)

您的操作永远不会被调用,因为UIGestureRecognizer没有关于要识别哪种手势的固有信息。只有它的具体子类。

答案 1 :(得分:0)

在将alpha更改为1.0并且无法同时识别时,您似乎正在添加多个手势识别器。隐藏和删除headerView时删除所有手势识别器,因为您不再需要它,并在添加回headerView时添加一个,它应该可以工作。或者你也可以让手势识别器在隐藏headerView时,因为它无论如何都不会工作,并在添加另一个之前检查是否存在。

if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)

        // add touch gesture recognizer to stack view header
        let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
        self.headerView.addGestureRecognizer(tapFind)
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.headerView.gestureRecognizers?.forEach({self.headerView.removeGestureRecognizer($0)})
        self.stack.removeArrangedSubview(self.headerView)
    }
}

if isShown {
    stack.alpha = 1.0
    self.isStackShown = true
    DispatchQueue.main.async {
        self.headerView.isHidden = !isShown
        self.stack.addArrangedSubview(self.headerView)
        if self.headerView.gestureRecognizers?.isEmpty != false{
           // add touch gesture recognizer to stack view header
           let tapFind = UIGestureRecognizer(target: self, action: #selector(self.handleFindTap))
           self.headerView.addGestureRecognizer(tapFind)
        }
    }
} else {
    stack.alpha = 0.0
    self.isStackShown = false
    DispatchQueue.main.async {
        self.headerView.isHidden = isShown
        self.stack.removeArrangedSubview(self.headerView)
    }
}