使用点击手势(iOS)在点击时更改UIView的背景色

使用点击手势(iOS)在点击时更改UIView的背景色,ios,swift,xcode,uiview,Ios,Swift,Xcode,Uiview,我想在点击时更改UIView的颜色,并在点击事件后将其更改回原来的颜色 我已经实现了这两种方法,但它们的行为并没有给我所需的结果 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) backgroundColor = UIColor.white }

我想在点击时更改
UIView
的颜色,并在点击事件后将其更改回原来的颜色

我已经实现了这两种方法,但它们的行为并没有给我所需的结果

     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        backgroundColor = UIColor.white
    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        backgroundColor = UIColor.gray
    }

override func touchsbegind(touch:Set,带有事件:UIEvent?){
super.touchesbeated(touches,with:event)
backgroundColor=UIColor.white
}
覆盖函数touchesend(touchs:Set,带有事件:UIEvent?){
super.touchesend(触摸,带有:事件)
backgroundColor=UIColor.gray
}
这两种方法都可以工作,但按一下
ui查看
2秒钟后就可以工作了。此外,按下后,它不会将
UIView
的颜色变回白色(简而言之,在我重新启动应用程序之前,它一直保持灰色)
我在
UIView

上使用点击手势,而不是覆盖
触摸开始
触摸结束
方法,您可以添加自己的手势识别器。受此启发,您可以做以下事情:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .gray
        setupTap()
    }

    func setupTap() {
        let touchDown = UILongPressGestureRecognizer(target:self, action: #selector(didTouchDown))
        touchDown.minimumPressDuration = 0
        view.addGestureRecognizer(touchDown)
    }

    @objc func didTouchDown(gesture: UILongPressGestureRecognizer) {
        if gesture.state == .began {
            view.backgroundColor = .white
        } else if gesture.state == .ended || gesture.state == .cancelled {
            view.backgroundColor = .gray
        }
    }
}