01
效果演示
上方:扩展的滑块组件及其状态显示
下方:默认的滑块组件及其状态显示
扩展的滑块组件支持拖拽开始/拖拽/拖拽结束事件的回调,同时也扩展了当前进度的展示
02
使用方法
直接将 SliderEx 预制件放在需要的地方
声明 SliderEx 的变量
@property(SliderEx)
sliderEx: SliderEx = null;
在代码中注册拖拽事件回调
this.sliderEx.handleDragStart((progress: number) => {
this.labelSliderEx.string = "拖拽开始:" + progress;
});
this.sliderEx.handleDragMove((progress: number) => {
this.labelSliderEx.string = "拖拽中:" + progress;
});
this.sliderEx.handleDragEnd((progress: number) => {
this.labelSliderEx.string = "拖拽结束:" + progress;
});
03
实现方法
Slider 的源码中已经注册了拖拽事件的函数,所以我们只需要继承 Slider,然后重写(override)对应的拖拽事件
源码路径:
resources\engine\cocos2d\core\components\CCSlider.js
在触摸事件处理函数中,根据 Slider 的进度设置当前进度条的宽度,并调用对应的回调方法
private handleTouchEvent(callback: (progress: number) => void) {
this.nodeProgress.width = this.node.width * this.progress;
if (callback) {
callback(this.progress);
}
}
完整的代码:
/**
* @author 渡鸦
* @description 扩展滑块拖拽事件及当前进度展示
*/
const { ccclass, property } = cc._decorator;
@ccclass
export default class SliderEx extends cc.Slider {
@property(cc.Node)
nodeProgress: cc.Node = null;
private _handleDragStart: (progress: number) => void = null;
private _handleDragMove: (progress: number) => void = null;
private _handleDragEnd: (progress: number) => void = null;
private __preload() {
super.__preload();
let widget = this.node.getComponent(cc.Widget);
if (widget) {
widget.updateAlignment();
}
}
private _onHandleDragStart(event: cc.Event.EventTouch) {
super._onHandleDragStart(event);
if (this._handleDragStart) {
this._handleDragStart(this.progress);
}
}
private _onTouchBegan(event) {
if (!this.handle) { return; }
super._onTouchBegan(event);
this.handleTouchEvent(this._handleDragStart);
}
private _onTouchMoved(event) {
if (!this.handle) { return; }
super._onTouchMoved(event);
this.handleTouchEvent(this._handleDragMove);
}
private _onTouchEnded(event) {
super._onTouchEnded(event);
this.handleTouchEvent(this._handleDragEnd);
}
private _onTouchCancelled(event) {
super._onTouchCancelled(event);
this.handleTouchEvent(this._handleDragEnd);
}
private _updateHandlePosition() {
if (!this.handle) { return; }
super._updateHandlePosition();
this.nodeProgress.width = this.node.width * this.progress;
}
private handleTouchEvent(callback: (progress: number) => void) {
this.nodeProgress.width = this.node.width * this.progress;
if (callback) {
callback(this.progress);
}
}
/**
* 拖拽开始事件回调
* @param callback
*/
handleDragStart(callback: (progress: number) => void) {
this._handleDragStart = callback;
}
/**
* 拖拽中事件回调
* @param callback
*/
handleDragMove(callback: (progress: number) => void) {
this._handleDragMove = callback;
}
/**
* 拖拽结束事件回调
* @param callback
*/
handleDragEnd(callback: (progress: number) => void) {
this._handleDragEnd = callback;
}
/**
* 设置进度
* @param value
*/
setProgress(value: number) {
if (!this._dragging) {
this.progress = value;
this.nodeProgress.width = this.node.width * value;
}
}
}
git:
https://gitee.com/Valiancer/raven-kit-open.git
demo:
公众号回复:SliderEx
更多教程
请扫码关注