简体   繁体   English

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

[英]Change background color of UIView on tap using tap gesture (iOS)

I want to change color of UIView when it's tap and change it back to it's original color after tap event 我想在点击时更改UIView颜色,并在点击事件后将其更改回原始颜色

I already implemented these 2 methods but their behavior is not giving me required results 我已经实现了这两种方法,但是它们的行为并未给我所需的结果

     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
    }

These 2 methods work but after press tap on UIView for 2 seconds then it works. 这两种方法都可以,但是在按下UIView 2秒钟后便可以使用。 Moreover it doesn't change the color of UIView back to white after pressing it (In short it stays gray until I restart the app) I am using tap gestures on UIView 此外,它不会在按下后将UIView的颜色变回白色(总之直到我重新启动应用程序,它都会保持灰色)。我在UIView上使用点击手势

Instead of overriding touchesBegan and touchesEnded methods, you could add your own gesture recognizer. 您可以添加自己的手势识别器,而不是覆盖touchesBegantouchesEnded方法。 Inspired from this answer , you could do something like: 这个答案中得到启发,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM