【问题标题】:Change background color of UIView on tap using tap gesture (iOS)使用点击手势更改 UIView 的背景颜色(iOS)
【发布时间】:2019-04-16 14:32:11
【问题描述】:

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

这两种方法有效,但在按下UIView 2 秒后,它就有效了。此外,它不会在按下后将UIView 的颜色改回白色(简而言之,在我重新启动应用程序之前它会保持灰色) 我在UIView上使用轻击手势

【问题讨论】:

    标签: ios swift xcode uiview


    【解决方案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
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2013-02-22
      • 2011-07-28
      • 1970-01-01
      • 2014-09-25
      • 2022-12-22
      • 1970-01-01
      相关资源
      最近更新 更多