一、问题现象
export default class PageViewTest extends cc.Component {
@property(cc.PageView)
pageView: cc.PageView = null;
onLoad() {
for (let i = 0; i < 10; i++) {
let node = cc.instantiate(this.tankItem);
node.active = true;
this.pageView.addPage(node);
let sprite = node.getChildByName("tankicon").getComponent(cc.Sprite);
this.tankList[i] = sprite.node;
sprite.node.scale = 1.5;
sprite.node.color = GameVoManager.getInstance.gameInfo.topTankId >= (i + 1) ? cc.Color.WHITE : cc.Color.BLACK;
Manager.spAtlas.getTankIconByResPath(data.icon).then(res => {
if (!res) return;
sprite.spriteFrame = res;
});
}
}
this.pageView.scrollToPage(this.useTankId - 1, 0.1);
}
在这段代码中
this.pageView.scrollToPage(this.useTankId - 1, 0.1)
无法生效,进入界面后需要点击鼠标才能生效。scrollToPage第一个参数表示页面id、第二参数表示页面滚动耗时,并不是延迟生效时间:
!#zh 滚动到指定页面
@param idx index of page.
@param timeInSecond scrolling time
*/
scrollToPage(idx: number, timeInSecond: number): void;
二、解决方案
通过调用 schedule 函数,延迟执行,scrollToPage可不用点击鼠标即可生效
this.pageView.schedule(()=>{
this.pageView.scrollToPage(this.useTankId - 1,0.1);
},0.1);
二、原因剖析
这可能是因为 PageView 组件在初始化时没有正确设置,或者是因为页面渲染或者事件处理导致的问题。
这里采用延迟调用的方式规避了。如何采用更好的方案,确保 scrollToPage 方法可以直接调用,希望有了解的高手可以分享下。