/** @format */ import {LANGUAGE_TYPE} from '../enums/Enum' import {ccUtils} from '../utils/ccUtils' const {ccclass, property, executeInEditMode} = cc._decorator @ccclass @executeInEditMode export default class Switch extends cc.Component { @property({displayName: '是否启用'}) interact: boolean = false @property({type: cc.Boolean}) get isChecked(): boolean { return this._isChecked } set isChecked(value: boolean) { if (this.interact) { this._isChecked = value this.updateTogglePosition(this.isClicked) if (this.isClicked) this.emitCheckEvents() this.isClicked = false } } @property({type: cc.Node, displayName: '开启滑块'}) switchOnNode: cc.Node = null @property({type: cc.Node, displayName: '关闭滑块'}) switchOffNode: cc.Node = null @property({type: cc.Node, displayName: '选择背景'}) background: cc.Node = null @property({displayName: '选择背景开启颜色'}) bgOnColor: cc.Color = cc.Color.WHITE.fromHEX('#FAC73E') @property({displayName: '选择背景关闭颜色'}) bgOffColor: cc.Color = cc.Color.WHITE.fromHEX('#5B5B5B') @property({displayName: '滑动起点'}) onPosition: cc.Vec2 = cc.v2(50, 0) @property({displayName: '滑动终点'}) offPosition: cc.Vec2 = cc.v2(-50, 0) @property() private _isChecked: boolean = false isClicked: boolean = false // 定义一个事件 @property({type: [cc.Component.EventHandler]}) checkEvents: cc.Component.EventHandler[] = [] onLoad() { this.updateTogglePosition(false) this.node.on(cc.Node.EventType.TOUCH_END, this.onToggle, this) } onDestroy() { this.node.off(cc.Node.EventType.TOUCH_END, this.onToggle, this) } onToggle() { this.isClicked = true this.isChecked = !this.isChecked } updateChecked(value: boolean) { this._isChecked = value this.updateTogglePosition(false) } updateTogglePosition(animated: boolean) { if (!this.switchOnNode || !this.switchOffNode) return this.switchOnNode.active = this.isChecked this.switchOffNode.active = !this.isChecked let switchNode = this.isChecked ? this.switchOnNode : this.switchOffNode let position = this.isChecked ? this.onPosition : this.offPosition let opacity = this.isChecked ? 255 : 0 if (animated) { switchNode.setPosition(this.isChecked ? this.offPosition : this.onPosition) cc.tween(switchNode) .to(0.2, {position: cc.v3(position)}) .start() if (this.background) cc.tween(this.background).to(0.2, {opacity: opacity}).start() } else { switchNode.setPosition(position) } if (this.background) this.background.color = this.isChecked ? this.bgOnColor : this.bgOffColor } emitCheckEvents() { cc.Component.EventHandler.emitEvents(this.checkEvents, this.isChecked) } }