按下时如何使 UIView 改变颜色? [英] How to make UIView change color when pressed?

查看:29
本文介绍了按下时如何使 UIView 改变颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让 UIView 在按下后高亮显示并在释放后恢复正常颜色.这样做的最佳做法是什么?

I would like to make a UIView highlighted after it's pressed and return to the normal color after release. What is the best practise for doing this?

推荐答案

UIView 的子类:

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.blue
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

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

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

Apple 关于覆盖 touchesBegantouchesEnded:

Apple about overriding touchesBegan and touchesEnded:

创建自己的子类时,调用super来转发任何事件你不处理自己.如果您在没有覆盖此方法的情况下调用 super(一种常用模式),您还必须覆盖另一个处理触摸事件的方法[即touchesEndedtouchesMovedtouchesCancelled],即使你的实现什么都没有.

When creating your own subclasses, call super to forward any events that you do not handle yourself. If you override this method without calling super (a common use pattern), you must also override the other methods for handling touch events [i.e. touchesEnded, touchesMoved, touchesCancelled], even if your implementations do nothing.

进一步阅读:

https://developer.apple.com/documentation/uikit/uiview

继承 UIView 的正确做法?

这篇关于按下时如何使 UIView 改变颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆