目的:需要根据玩家自主选择时间来展示界面
思路:
1、先用CocosStudio创建一个ScrollView,如果需要分别选择年、月、日、小时、分钟 则创建对应个数的ScrollView,如下图:
2、在对应的ScrollView里创建Text,添加到对应的ScrollView里,如下,列举一个年的例子,其他类似:
this.yearScroller = this.getChildFromRoot("yearScroller");
this.initTimeSelect(this._curMounth,this.monthScroller,this.dateScroller,0,this.yearScroller,this.timeSroller);
initTimeSelect:function (monthNum,monthSelect,daySelect,monthIndex,yearSelect,timeSelect) {
var now = new Date();
if(yearSelect){
yearSelect.setInnerContainerSize(cc.size(yearSelect.width,(this._maxYear + 2) * this._listItemHeight));
yearSelect.setInertiaScrollEnabled(false);
yearSelect.addTouchEventListener(this.onTouch.bind(this));
yearSelect.selectIndex = 0;
for(var i = 0; i < this._maxYear; i++){
var time = new Date();
time.setFullYear(now.getFullYear() + i);
var text = new ccui.Text();
text.setFontName(dt.FontConfig.Droid_Sans);
text.setFontSize(30);
text.setTextColor(cc.color("#7a7299"));
text.height = this._listItemHeight;
text.width = 120;
text.x = yearSelect.width/2 - 30;
text.y = 5 + (1 + i) * this._listItemHeight;
text.setAnchorPoint(cc.p(0,0));
var yearStr = time.getFullYear();
text.setString(yearStr);
yearSelect.addChild(text);
}
yearSelect.setInnerContainerPosition(cc.p(0,0));
},
onTouch:function (scrollView,event) {
if(event == ccui.Widget.TOUCH_ENDED || event == ccui.Widget.TOUCH_CANCELED){
var currentY = -scrollView.getInnerContainerPosition().y;
var index = Math.floor((currentY / this._listItemHeight));
if(currentY - index * this._listItemHeight > 20){
index += 1;
}
cc.log(currentY + "--" + index + "--" + scrollView.getInnerContainerSize().height);
scrollView.selectIndex = index;
var minY = scrollView.height - scrollView.getInnerContainerSize().height;
var h = - minY;
var percentage = (-index * this._listItemHeight - minY) * 100 / h;
scrollView.scrollToPercentVertical(percentage,0.2,false);
}
},
最终效果如下图: