一 控件介紹
針對Cocos Creator,上新一個小型好用的下拉列表控件,動畫平滑,設(shè)置多樣,數(shù)據(jù)驅(qū)動,點擊空白收起,可擴展虛擬列表。
Cocos Creator 引擎中沒有提供一款拿來即用的下拉列表控件,參考多種情景考慮,設(shè)計實現(xiàn)了這款小型但極其實用的下拉列表控件,拿來即用,配置靈活。
二 控件安裝
使用控件非常簡單,只需要拷貝demo項目中兩個文件 ButtonDropdownList.prefab, ButtonDropdownList.js 到您的工程中的prefabs文件夾中即可。實用前,將ButtonDropdownList.prefab 拖入畫布中就可以。
三 API說明
1. ButtonDropdownList 啟動參數(shù)
啟動參數(shù)可以在creator 圖形化界面填入,但是為了不受預(yù)制體的維護影響,建議通過初 始化腳本接口傳入啟動參數(shù)。
buttonDropdownList.initDropdownList(optionButtonTemplate, options, titleButtonTemplate, selectedOptionButtonTemplate)
參數(shù)
- optionButtonTemplate: cc.Prefab 選項按鈕模板(Button)
- options? {
placeHolder?: String 當(dāng)placeholder為空的時候,默認(rèn)選項為列表第一個
hideSelectedOption?: Boolean 打開列表的時候,當(dāng)前選中的選項是否在列表中顯示 默認(rèn)為true
paddingLeftAndRight?: Number 下拉框兩側(cè)邊距 默認(rèn)為5
paddingTopAndBottom?: Number 下拉框上下邊距 默認(rèn)為5
spacingY?: Number 選項之間間隙 默認(rèn)為3
marginTop?: Number 下拉列表距標(biāo)題按鈕距離 默認(rèn)為0
maxListHeight?: Number 列表限高 默認(rèn)為0:不限制高度
listBackground?: cc.SpriteFrame 下拉列表背景圖片
optionButtonSize?: cc.Size 下來選項按鈕大小
}
- titleButtonTemplate?: cc.Prefab 頭部按鈕模板(Button),如果不設(shè)置,默認(rèn)使用optionButtonTemplate
- selectedOptionButtonTemplate?: cc.Prefab 列表中選中的按鈕模板(Button),如果不設(shè)置,默認(rèn)使用optionButtonTemplate,只有當(dāng) hideSelectedOption = false 的時候有效
初始化demo
initDropdownListSimple(){
let dropdownListController = this.dropdownList.getComponent("ButtonDropdownList");
dropdownListController.initDropdownList(this.optionButtonTemplate, { // 初始化啟動參數(shù)
placeHolder: '請選擇',
paddingLeftAndRight: 8,
paddingTopAndBottom: 10,
spacingY: 5,
marginTop: 0,
hideSelectedOption: true,
optionButtonSize: new cc.size(120, 40)
});
let dataList = [];
for(let i = 0; i < 10; i++){
dataList.push({
key: i +'',
label: '選項 ' + i
});
}
this._dataList1 = dataList;
dropdownListController.addSelectionChangedEventHandler((selectionData)=>{ // 注冊選項變更事件
this.lbSelection1.string = 'Selected: '+ selectionData.key;
}, this);
dropdownListController.setOptionDataList(dataList, '1'); // 綁定列表,同時設(shè)置默認(rèn)選項key
}
只設(shè)置 optionButtonTemplate,所有按鈕一樣

設(shè)置頭部按鈕樣式 titleButtonTemplate

設(shè)置頭部按鈕樣式 titleButtonTemplate 和 選中按鈕樣式 selectedOptionButtonTemplate

2. ButtonDropdownList 功能接口
getOptionDataList(): any[]
獲取下拉列表數(shù)據(jù) [{key, label}]
getSelectKey(): String
獲取當(dāng)前選中的key
setSelection(key: String, triggerEvent: Boolean): void
設(shè)定選中選項。key代表選中選項的key值,triggerEvent代表是否觸發(fā)選項變更事件 默認(rèn) false
addSelectionChangedEventHandler(handler: Function, thisObj: any): void
注冊選項變更事件處理方法,如果注冊了此事件,則不會觸發(fā)emit(ButtonDropdownList.Events.SELECTTION_CHANGED)。handler(selectionData)為選項修改回調(diào)函數(shù), thisObj回調(diào)函數(shù)的this對象
setOptionDataList(dataList: any[], selectedKey: String): void
初始化下拉列表數(shù)據(jù)。dataList 為下拉列表數(shù)據(jù) [{key, label}], selectedKey為下拉列表默認(rèn)選項
reset(): void
重置控件,列表收起。
四 下拉列表虛擬布局?jǐn)U展
理論簡單,配合CCVirtualGridList控件,將按鈕列表容器listContent替換成CCVirtualGridList,源碼少量改動。