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

时间:2019-04-16 14:32:11

标签: ios swift xcode uiview

我想在点击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
    }

这2种方法都可以,但是在按住UIView的同时点击2秒钟,然后就可以使用。此外,按下UIView后,它的颜色不会变回白色(总之直到我重新启动应用程序,它都会保持灰色) 我在UIView

上使用了轻按手势

1 个答案:

答案 0 :(得分:1)

您可以添加自己的手势识别器,而不是覆盖touchesBegantouchesEnded方法。受this answer的启发,您可以执行以下操作:

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