List.ts 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145
  1. const { ccclass, property, disallowMultiple, menu, executionOrder, requireComponent } = _decorator;
  2. import { Node, Component, Enum, tween, _decorator, EventHandler, Tween, ScrollView, Prefab, Layout, Vec2, Size, NodePool, isValid, instantiate, Vec3, Widget, UITransform, CCFloat, CCBoolean, CCInteger } from 'cc';
  3. import { DEV } from 'cc/env';
  4. import ListItem from './ListItem';
  5. enum TemplateType {
  6. NODE = 1,
  7. PREFAB = 2,
  8. }
  9. enum SlideType {
  10. NORMAL = 1,//普通
  11. ADHERING = 2,//粘附模式,将强制关闭滚动惯性
  12. PAGE = 3,//页面模式,将强制关闭滚动惯性
  13. }
  14. enum SelectedType {
  15. NONE = 0,
  16. SINGLE = 1,//单选
  17. MULT = 2,//多选
  18. }
  19. @ccclass
  20. @disallowMultiple()
  21. @menu('List')
  22. @requireComponent(ScrollView)
  23. //脚本生命周期回调的执行优先级。小于 0 的脚本将优先执行,大于 0 的脚本将最后执行。该优先级只对 onLoad, onEnable, start, update 和 lateUpdate 有效,对 onDisable 和 onDestroy 无效。
  24. @executionOrder(-5000)
  25. export default class List extends Component {
  26. //模板类型
  27. @property({ type: Enum(TemplateType), tooltip: DEV && '模板类型', })
  28. private templateType: TemplateType = TemplateType.NODE;
  29. //模板Item(Node)
  30. @property({
  31. type: Node,
  32. tooltip: DEV && '模板Item',
  33. visible() { return this.templateType == TemplateType.NODE; }
  34. })
  35. tmpNode: Node = null;
  36. //模板Item(Prefab)
  37. @property({
  38. type: Prefab,
  39. tooltip: DEV && '模板Item',
  40. visible() { return this.templateType == TemplateType.PREFAB; }
  41. })
  42. tmpPrefab: Prefab = null;
  43. //滑动模式
  44. @property({})
  45. private _slideMode: SlideType = SlideType.NORMAL;
  46. @property({
  47. type: Enum(SlideType),
  48. tooltip: DEV && '滑动模式'
  49. })
  50. set slideMode(val: SlideType) {
  51. this._slideMode = val;
  52. }
  53. get slideMode() {
  54. return this._slideMode;
  55. }
  56. //翻页作用距离
  57. @property({
  58. type: CCFloat,
  59. range: [0, 1, .1],
  60. tooltip: DEV && '翻页作用距离',
  61. slide: true,
  62. visible() { return this._slideMode == SlideType.PAGE; }
  63. })
  64. public pageDistance: number = .3;
  65. //页面改变事件
  66. @property({
  67. type: EventHandler,
  68. tooltip: DEV && '页面改变事件',
  69. visible() { return this._slideMode == SlideType.PAGE; }
  70. })
  71. private pageChangeEvent: EventHandler = new EventHandler();
  72. //是否为虚拟列表(动态列表)
  73. @property({})
  74. private _virtual: boolean = true;
  75. @property({
  76. type: CCBoolean,
  77. tooltip: DEV && '是否为虚拟列表(动态列表)'
  78. })
  79. set virtual(val: boolean) {
  80. if (val != null)
  81. this._virtual = val;
  82. if (!DEV && this._numItems != 0) {
  83. this._onScrolling();
  84. }
  85. }
  86. get virtual() {
  87. return this._virtual;
  88. }
  89. //是否为循环列表
  90. @property({
  91. tooltip: DEV && '是否为循环列表',
  92. visible() {
  93. let val: boolean = /*this.virtual &&*/ this.slideMode == SlideType.NORMAL;
  94. if (!val)
  95. this.cyclic = false;
  96. return val;
  97. }
  98. })
  99. public cyclic: boolean = false;
  100. //缺省居中
  101. @property({
  102. tooltip: DEV && 'Item数量不足以填满Content时,是否居中显示Item(不支持Grid布局)',
  103. visible() { return this.virtual; }
  104. })
  105. public lackCenter: boolean = false;
  106. //缺省可滑动
  107. @property({
  108. tooltip: DEV && 'Item数量不足以填满Content时,是否可滑动',
  109. visible() {
  110. let val: boolean = this.virtual && !this.lackCenter;
  111. if (!val)
  112. this.lackSlide = false;
  113. return val;
  114. }
  115. })
  116. public lackSlide: boolean = false;
  117. //刷新频率
  118. @property({ type: CCInteger })
  119. private _updateRate: number = 0;
  120. @property({
  121. type: CCInteger,
  122. range: [0, 6, 1],
  123. tooltip: DEV && '刷新频率(值越大刷新频率越低、性能越高)',
  124. slide: true,
  125. })
  126. set updateRate(val: number) {
  127. if (val >= 0 && val <= 6) {
  128. this._updateRate = val;
  129. }
  130. }
  131. get updateRate() {
  132. return this._updateRate;
  133. }
  134. //分帧渲染(每帧渲染的Item数量(<=0时关闭分帧渲染))
  135. @property({
  136. type: CCInteger,
  137. range: [0, 12, 1],
  138. tooltip: DEV && '逐帧渲染时,每帧渲染的Item数量(<=0时关闭分帧渲染)',
  139. slide: true,
  140. })
  141. public frameByFrameRenderNum: number = 0;
  142. //渲染事件(渲染器)
  143. @property({
  144. type: EventHandler,
  145. tooltip: DEV && '渲染事件(渲染器)',
  146. })
  147. public renderEvent: EventHandler = new EventHandler();
  148. //选择模式
  149. @property({
  150. type: Enum(SelectedType),
  151. tooltip: DEV && '选择模式'
  152. })
  153. public selectedMode: SelectedType = SelectedType.NONE;
  154. //触发选择事件
  155. @property({
  156. type: EventHandler,
  157. tooltip: DEV && '触发选择事件',
  158. visible() { return this.selectedMode > SelectedType.NONE; }
  159. })
  160. public selectedEvent: EventHandler = new EventHandler();
  161. @property({
  162. tooltip: DEV && '是否重复响应单选事件',
  163. visible() { return this.selectedMode == SelectedType.SINGLE; }
  164. })
  165. public repeatEventSingle: boolean = false;
  166. //当前选择id
  167. private _selectedId: number = -1;
  168. private _lastSelectedId: number;
  169. private multSelected: number[];
  170. set selectedId(val: number) {
  171. let t: any = this;
  172. let item: any;
  173. switch (t.selectedMode) {
  174. case SelectedType.SINGLE: {
  175. if (!t.repeatEventSingle && val == t._selectedId)
  176. return;
  177. item = t.getItemByListId(val);
  178. // if (!item && val >= 0)
  179. // return;
  180. let listItem: ListItem;
  181. if (t._selectedId >= 0)
  182. t._lastSelectedId = t._selectedId;
  183. else //如果<0则取消选择,把_lastSelectedId也置空吧,如果以后有特殊需求再改吧。
  184. t._lastSelectedId = null;
  185. t._selectedId = val;
  186. if (item) {
  187. listItem = item.getComponent(ListItem);
  188. listItem.selected = true;
  189. }
  190. if (t._lastSelectedId >= 0 && t._lastSelectedId != t._selectedId) {
  191. let lastItem: any = t.getItemByListId(t._lastSelectedId);
  192. if (lastItem) {
  193. lastItem.getComponent(ListItem).selected = false;
  194. }
  195. }
  196. if (t.selectedEvent) {
  197. EventHandler.emitEvents([t.selectedEvent], item, val % this._actualNumItems, t._lastSelectedId == null ? null : (t._lastSelectedId % this._actualNumItems));
  198. }
  199. break;
  200. }
  201. case SelectedType.MULT: {
  202. item = t.getItemByListId(val);
  203. if (!item)
  204. return;
  205. let listItem = item.getComponent(ListItem);
  206. if (t._selectedId >= 0)
  207. t._lastSelectedId = t._selectedId;
  208. t._selectedId = val;
  209. let bool: boolean = !listItem.selected;
  210. listItem.selected = bool;
  211. let sub: number = t.multSelected.indexOf(val);
  212. if (bool && sub < 0) {
  213. t.multSelected.push(val);
  214. } else if (!bool && sub >= 0) {
  215. t.multSelected.splice(sub, 1);
  216. }
  217. if (t.selectedEvent) {
  218. EventHandler.emitEvents([t.selectedEvent], item, val % this._actualNumItems, t._lastSelectedId == null ? null : (t._lastSelectedId % this._actualNumItems), bool);
  219. }
  220. break;
  221. }
  222. }
  223. }
  224. get selectedId() {
  225. return this._selectedId;
  226. }
  227. private _forceUpdate: boolean = false;
  228. private _align: number;
  229. private _horizontalDir: number;
  230. private _verticalDir: number;
  231. private _startAxis: number;
  232. private _alignCalcType: number;
  233. public content: Node;
  234. private _contentUt: UITransform;
  235. private firstListId: number;
  236. public displayItemNum: number;
  237. private _updateDone: boolean = true;
  238. private _updateCounter: number;
  239. public _actualNumItems: number;
  240. private _cyclicNum: number;
  241. private _cyclicPos1: number;
  242. private _cyclicPos2: number;
  243. //列表数量
  244. @property({
  245. serializable: false
  246. })
  247. private _numItems: number = 0;
  248. set numItems(val: number) {
  249. console.log("---------------------------------set numItems:",val)
  250. let t = this;
  251. if (!t.checkInited(false))
  252. return;
  253. if (val == null || val < 0) {
  254. console.error('numItems set the wrong::', val);
  255. return;
  256. }
  257. t._actualNumItems = t._numItems = val;
  258. t._forceUpdate = true;
  259. if (t._virtual) {
  260. t._resizeContent();
  261. if (t.cyclic) {
  262. t._numItems = t._cyclicNum * t._numItems;
  263. }
  264. t._onScrolling();
  265. if (!t.frameByFrameRenderNum && t.slideMode == SlideType.PAGE)
  266. t.curPageNum = t.nearestListId;
  267. } else {
  268. if (t.cyclic) {
  269. t._resizeContent();
  270. t._numItems = t._cyclicNum * t._numItems;
  271. }
  272. let layout: Layout = t.content.getComponent(Layout);
  273. if (layout) {
  274. layout.enabled = true;
  275. }
  276. t._delRedundantItem();
  277. t.firstListId = 0;
  278. if (t.frameByFrameRenderNum > 0) {
  279. //先渲染几个出来
  280. let len: number = t.frameByFrameRenderNum > t._numItems ? t._numItems : t.frameByFrameRenderNum;
  281. for (let n: number = 0; n < len; n++) {
  282. t._createOrUpdateItem2(n);
  283. }
  284. if (t.frameByFrameRenderNum < t._numItems) {
  285. t._updateCounter = t.frameByFrameRenderNum;
  286. t._updateDone = false;
  287. }
  288. } else {
  289. for (let n: number = 0; n < t._numItems; n++) {
  290. t._createOrUpdateItem2(n);
  291. }
  292. t.displayItemNum = t._numItems;
  293. }
  294. }
  295. }
  296. get numItems() {
  297. return this._actualNumItems;
  298. }
  299. private _inited: boolean = false;
  300. private _scrollView: ScrollView;
  301. get scrollView() {
  302. return this._scrollView;
  303. }
  304. private _layout: Layout;
  305. private _resizeMode: number;
  306. private _topGap: number;
  307. private _rightGap: number;
  308. private _bottomGap: number;
  309. private _leftGap: number;
  310. private _columnGap: number;
  311. private _lineGap: number;
  312. private _colLineNum: number;
  313. private _lastDisplayData: number[];
  314. public displayData: any[];
  315. private _pool: NodePool;
  316. private _itemTmp: any;
  317. private _itemTmpUt: UITransform;
  318. private _needUpdateWidget: boolean = false;
  319. private _itemSize: Size;
  320. private _sizeType: boolean;
  321. public _customSize: any;
  322. private frameCount: number;
  323. private _aniDelRuning: boolean = false;
  324. private _aniDelCB: Function;
  325. private _aniDelItem: any;
  326. private _aniDelBeforePos: Vec2;
  327. private _aniDelBeforeScale: number;
  328. private viewTop: number;
  329. private viewRight: number;
  330. private viewBottom: number;
  331. private viewLeft: number;
  332. private _doneAfterUpdate: boolean = false;
  333. private elasticTop: number;
  334. private elasticRight: number;
  335. private elasticBottom: number;
  336. private elasticLeft: number;
  337. private scrollToListId: number;
  338. private adhering: boolean = false;
  339. private _adheringBarrier: boolean = false;
  340. private nearestListId: number;
  341. public curPageNum: number = 0;
  342. private _beganPos: number;
  343. private _scrollPos: number;
  344. private _curScrollIsTouch: boolean;//当前滑动是否为手动
  345. private _scrollToListId: number;
  346. private _scrollToEndTime: number;
  347. private _scrollToSo: any;
  348. private _lack: boolean;
  349. private _allItemSize: number;
  350. private _allItemSizeNoEdge: number;
  351. private _scrollItem: any;//当前控制 ScrollView 滚动的 Item
  352. private _thisNodeUt: UITransform;
  353. //----------------------------------------------------------------------------
  354. onLoad() {
  355. this._init();
  356. }
  357. onDestroy() {
  358. let t: any = this;
  359. if (isValid(t._itemTmp))
  360. t._itemTmp.destroy();
  361. if (isValid(t.tmpNode))
  362. t.tmpNode.destroy();
  363. t._pool && t._pool.clear();
  364. }
  365. onEnable() {
  366. // if (!EDITOR)
  367. this._registerEvent();
  368. this._init();
  369. // 处理重新显示后,有可能上一次的动画移除还未播放完毕,导致动画卡住的问题
  370. if (this._aniDelRuning) {
  371. this._aniDelRuning = false;
  372. if (this._aniDelItem) {
  373. if (this._aniDelBeforePos) {
  374. this._aniDelItem.position = this._aniDelBeforePos;
  375. delete this._aniDelBeforePos;
  376. }
  377. if (this._aniDelBeforeScale) {
  378. this._aniDelItem.scale = this._aniDelBeforeScale;
  379. delete this._aniDelBeforeScale;
  380. }
  381. delete this._aniDelItem;
  382. }
  383. if (this._aniDelCB) {
  384. this._aniDelCB();
  385. delete this._aniDelCB;
  386. }
  387. }
  388. }
  389. onDisable() {
  390. // if (!EDITOR)
  391. this._unregisterEvent();
  392. }
  393. //注册事件
  394. _registerEvent() {
  395. let t: any = this;
  396. t.node.on(Node.EventType.TOUCH_START, t._onTouchStart, t);
  397. t.node.on('touch-up', t._onTouchUp, t);
  398. t.node.on(Node.EventType.TOUCH_CANCEL, t._onTouchCancelled, t);
  399. t.node.on('scroll-began', t._onScrollBegan, t);
  400. t.node.on('scroll-ended', t._onScrollEnded, t);
  401. t.node.on('scrolling', t._onScrolling, t);
  402. t.node.on(Node.EventType.SIZE_CHANGED, t._onSizeChanged, t);
  403. }
  404. //卸载事件
  405. _unregisterEvent() {
  406. let t: any = this;
  407. t.node.off(Node.EventType.TOUCH_START, t._onTouchStart, t);
  408. t.node.off('touch-up', t._onTouchUp, t);
  409. t.node.off(Node.EventType.TOUCH_CANCEL, t._onTouchCancelled, t);
  410. t.node.off('scroll-began', t._onScrollBegan, t);
  411. t.node.off('scroll-ended', t._onScrollEnded, t);
  412. t.node.off('scrolling', t._onScrolling, t);
  413. t.node.off(Node.EventType.SIZE_CHANGED, t._onSizeChanged, t);
  414. }
  415. //初始化各种..
  416. _init() {
  417. let t: any = this;
  418. if (t._inited)
  419. return;
  420. t._thisNodeUt = t.node.getComponent(UITransform);
  421. t._scrollView = t.node.getComponent(ScrollView);
  422. t.content = t._scrollView.content;
  423. t._contentUt = t.content.getComponent(UITransform);
  424. if (!t.content) {
  425. console.error(t.node.name + "'s ScrollView unset content!");
  426. return;
  427. }
  428. t._layout = t.content.getComponent(Layout);
  429. t._align = t._layout.type; //排列模式
  430. t._resizeMode = t._layout.resizeMode; //自适应模式
  431. t._startAxis = t._layout.startAxis;
  432. t._topGap = t._layout.paddingTop; //顶边距
  433. t._rightGap = t._layout.paddingRight; //右边距
  434. t._bottomGap = t._layout.paddingBottom; //底边距
  435. t._leftGap = t._layout.paddingLeft; //左边距
  436. t._columnGap = t._layout.spacingX; //列距
  437. t._lineGap = t._layout.spacingY; //行距
  438. t._colLineNum; //列数或行数(非GRID模式则=1,表示单列或单行);
  439. t._verticalDir = t._layout.verticalDirection; //垂直排列子节点的方向
  440. t._horizontalDir = t._layout.horizontalDirection; //水平排列子节点的方向
  441. t.setTemplateItem(instantiate(t.templateType == TemplateType.PREFAB ? t.tmpPrefab : t.tmpNode));
  442. // 特定的滑动模式处理
  443. if (t._slideMode == SlideType.ADHERING || t._slideMode == SlideType.PAGE) {
  444. t._scrollView.inertia = false;
  445. t._scrollView._onMouseWheel = function () {
  446. return;
  447. };
  448. }
  449. if (!t.virtual) // lackCenter 仅支持 Virtual 模式
  450. t.lackCenter = false;
  451. t._lastDisplayData = []; //最后一次刷新的数据
  452. t.displayData = []; //当前数据
  453. t._pool = new NodePool(); //这是个池子..
  454. t._forceUpdate = false; //是否强制更新
  455. t._updateCounter = 0; //当前分帧渲染帧数
  456. t._updateDone = true; //分帧渲染是否完成
  457. t.curPageNum = 0; //当前页数
  458. if (t.cyclic || 0) {
  459. t._scrollView._processAutoScrolling = this._processAutoScrolling.bind(t);
  460. t._scrollView._startBounceBackIfNeeded = function () {
  461. return false;
  462. }
  463. }
  464. switch (t._align) {
  465. case Layout.Type.HORIZONTAL: {
  466. switch (t._horizontalDir) {
  467. case Layout.HorizontalDirection.LEFT_TO_RIGHT:
  468. t._alignCalcType = 1;
  469. break;
  470. case Layout.HorizontalDirection.RIGHT_TO_LEFT:
  471. t._alignCalcType = 2;
  472. break;
  473. }
  474. break;
  475. }
  476. case Layout.Type.VERTICAL: {
  477. switch (t._verticalDir) {
  478. case Layout.VerticalDirection.TOP_TO_BOTTOM:
  479. t._alignCalcType = 3;
  480. break;
  481. case Layout.VerticalDirection.BOTTOM_TO_TOP:
  482. t._alignCalcType = 4;
  483. break;
  484. }
  485. break;
  486. }
  487. case Layout.Type.GRID: {
  488. switch (t._startAxis) {
  489. case Layout.AxisDirection.HORIZONTAL:
  490. switch (t._verticalDir) {
  491. case Layout.VerticalDirection.TOP_TO_BOTTOM:
  492. t._alignCalcType = 3;
  493. break;
  494. case Layout.VerticalDirection.BOTTOM_TO_TOP:
  495. t._alignCalcType = 4;
  496. break;
  497. }
  498. break;
  499. case Layout.AxisDirection.VERTICAL:
  500. switch (t._horizontalDir) {
  501. case Layout.HorizontalDirection.LEFT_TO_RIGHT:
  502. t._alignCalcType = 1;
  503. break;
  504. case Layout.HorizontalDirection.RIGHT_TO_LEFT:
  505. t._alignCalcType = 2;
  506. break;
  507. }
  508. break;
  509. }
  510. break;
  511. }
  512. }
  513. // 清空 content
  514. // t.content.children.forEach((child: Node) => {
  515. // child.removeFromParent();
  516. // if (child != t.tmpNode && child.isValid)
  517. // child.destroy();
  518. // });
  519. t.content.removeAllChildren();
  520. t._inited = true;
  521. }
  522. /**
  523. * 为了实现循环列表,必须覆写cc.ScrollView的某些函数
  524. * @param {Number} dt
  525. */
  526. _processAutoScrolling(dt: number) {
  527. // ------------- scroll-view 里定义的一些常量 -------------
  528. const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
  529. const EPSILON = 1e-4;
  530. const ZERO = new Vec3();
  531. const quintEaseOut = (time: number) => {
  532. time -= 1;
  533. return (time * time * time * time * time + 1);
  534. };
  535. // ------------- scroll-view 里定义的一些常量 -------------
  536. let sv: ScrollView = this._scrollView;
  537. const isAutoScrollBrake = sv['_isNecessaryAutoScrollBrake']();
  538. const brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
  539. sv['_autoScrollAccumulatedTime'] += dt * (1 / brakingFactor);
  540. let percentage = Math.min(1, sv['_autoScrollAccumulatedTime'] / sv['_autoScrollTotalTime']);
  541. if (sv['_autoScrollAttenuate']) {
  542. percentage = quintEaseOut(percentage);
  543. }
  544. const clonedAutoScrollTargetDelta = sv['_autoScrollTargetDelta'].clone();
  545. clonedAutoScrollTargetDelta.multiplyScalar(percentage);
  546. const clonedAutoScrollStartPosition = sv['_autoScrollStartPosition'].clone();
  547. clonedAutoScrollStartPosition.add(clonedAutoScrollTargetDelta);
  548. let reachedEnd = Math.abs(percentage - 1) <= EPSILON;
  549. const fireEvent = Math.abs(percentage - 1) <= sv['getScrollEndedEventTiming']();
  550. if (fireEvent && !sv['_isScrollEndedWithThresholdEventFired']) {
  551. sv['_dispatchEvent'](ScrollView.EventType.SCROLL_ENG_WITH_THRESHOLD);
  552. sv['_isScrollEndedWithThresholdEventFired'] = true;
  553. }
  554. if (sv['elastic']) {
  555. const brakeOffsetPosition = clonedAutoScrollStartPosition.clone();
  556. brakeOffsetPosition.subtract(sv['_autoScrollBrakingStartPosition']);
  557. if (isAutoScrollBrake) {
  558. brakeOffsetPosition.multiplyScalar(brakingFactor);
  559. }
  560. clonedAutoScrollStartPosition.set(sv['_autoScrollBrakingStartPosition']);
  561. clonedAutoScrollStartPosition.add(brakeOffsetPosition);
  562. } else {
  563. const moveDelta = clonedAutoScrollStartPosition.clone();
  564. moveDelta.subtract(sv['_getContentPosition']());
  565. const outOfBoundary = sv['_getHowMuchOutOfBoundary'](moveDelta);
  566. if (!outOfBoundary.equals(ZERO, EPSILON)) {
  567. clonedAutoScrollStartPosition.add(outOfBoundary);
  568. reachedEnd = true;
  569. }
  570. }
  571. if (reachedEnd) {
  572. sv['_autoScrolling'] = false;
  573. }
  574. const deltaMove = new Vec3(clonedAutoScrollStartPosition);
  575. deltaMove.subtract(sv['_getContentPosition']());
  576. sv['_clampDelta'](deltaMove);
  577. sv['_moveContent'](deltaMove, reachedEnd);
  578. sv['_dispatchEvent'](ScrollView.EventType.SCROLLING);
  579. if (!sv['_autoScrolling']) {
  580. sv['_isBouncing'] = false;
  581. sv['_scrolling'] = false;
  582. sv['_dispatchEvent'](ScrollView.EventType.SCROLL_ENDED);
  583. }
  584. }
  585. //设置模板Item
  586. setTemplateItem(item: any) {
  587. if (!item)
  588. return;
  589. let t: any = this;
  590. t._itemTmp = item;
  591. t._itemTmpUt = item.getComponent(UITransform);
  592. if (t._resizeMode == Layout.ResizeMode.CHILDREN)
  593. t._itemSize = t._layout.cellSize;
  594. else {
  595. let itemUt: UITransform = item.getComponent(UITransform);
  596. t._itemSize = new Size(itemUt.width, itemUt.height);
  597. }
  598. //获取ListItem,如果没有就取消选择模式
  599. let com: any = item.getComponent(ListItem);
  600. let remove = false;
  601. if (!com)
  602. remove = true;
  603. // if (com) {
  604. // if (!com._btnCom && !item.getComponent(cc.Button)) {
  605. // remove = true;
  606. // }
  607. // }
  608. if (remove) {
  609. t.selectedMode = SelectedType.NONE;
  610. }
  611. com = item.getComponent(Widget);
  612. if (com && com.enabled) {
  613. t._needUpdateWidget = true;
  614. }
  615. if (t.selectedMode == SelectedType.MULT)
  616. t.multSelected = [];
  617. switch (t._align) {
  618. case Layout.Type.HORIZONTAL:
  619. t._colLineNum = 1;
  620. t._sizeType = false;
  621. break;
  622. case Layout.Type.VERTICAL:
  623. t._colLineNum = 1;
  624. t._sizeType = true;
  625. break;
  626. case Layout.Type.GRID:
  627. switch (t._startAxis) {
  628. case Layout.AxisDirection.HORIZONTAL:
  629. //计算列数
  630. let trimW: number = t._contentUt.width - t._leftGap - t._rightGap;
  631. t._colLineNum = Math.floor((trimW + t._columnGap) / (t._itemSize.width + t._columnGap));
  632. t._sizeType = true;
  633. break;
  634. case Layout.AxisDirection.VERTICAL:
  635. //计算行数
  636. let trimH: number = t._contentUt.height - t._topGap - t._bottomGap;
  637. t._colLineNum = Math.floor((trimH + t._lineGap) / (t._itemSize.height + t._lineGap));
  638. t._sizeType = false;
  639. break;
  640. }
  641. break;
  642. }
  643. }
  644. /**
  645. * 检查是否初始化
  646. * @param {Boolean} printLog 是否打印错误信息
  647. * @returns
  648. */
  649. checkInited(printLog: boolean = true) {
  650. if (!this._inited) {
  651. if (printLog)
  652. console.error('List initialization not completed!');
  653. return false;
  654. }
  655. return true;
  656. }
  657. //禁用 Layout 组件,自行计算 Content Size
  658. _resizeContent() {
  659. let t: any = this;
  660. let result: number;
  661. switch (t._align) {
  662. case Layout.Type.HORIZONTAL: {
  663. if (t._customSize) {
  664. let fixed: any = t._getFixedSize(null);
  665. result = t._leftGap + fixed.val + (t._itemSize.width * (t._numItems - fixed.count)) + (t._columnGap * (t._numItems - 1)) + t._rightGap;
  666. } else {
  667. result = t._leftGap + (t._itemSize.width * t._numItems) + (t._columnGap * (t._numItems - 1)) + t._rightGap;
  668. }
  669. break;
  670. }
  671. case Layout.Type.VERTICAL: {
  672. if (t._customSize) {
  673. let fixed: any = t._getFixedSize(null);
  674. result = t._topGap + fixed.val + (t._itemSize.height * (t._numItems - fixed.count)) + (t._lineGap * (t._numItems - 1)) + t._bottomGap;
  675. } else {
  676. result = t._topGap + (t._itemSize.height * t._numItems) + (t._lineGap * (t._numItems - 1)) + t._bottomGap;
  677. }
  678. break;
  679. }
  680. case Layout.Type.GRID: {
  681. //网格模式不支持居中
  682. if (t.lackCenter)
  683. t.lackCenter = false;
  684. switch (t._startAxis) {
  685. case Layout.AxisDirection.HORIZONTAL:
  686. let lineNum: number = Math.ceil(t._numItems / t._colLineNum);
  687. result = t._topGap + (t._itemSize.height * lineNum) + (t._lineGap * (lineNum - 1)) + t._bottomGap;
  688. break;
  689. case Layout.AxisDirection.VERTICAL:
  690. let colNum: number = Math.ceil(t._numItems / t._colLineNum);
  691. result = t._leftGap + (t._itemSize.width * colNum) + (t._columnGap * (colNum - 1)) + t._rightGap;
  692. break;
  693. }
  694. break;
  695. }
  696. }
  697. let layout: Layout = t.content.getComponent(Layout);
  698. if (layout)
  699. layout.enabled = false;
  700. t._allItemSize = result;
  701. t._allItemSizeNoEdge = t._allItemSize - (t._sizeType ? (t._topGap + t._bottomGap) : (t._leftGap + t._rightGap));
  702. if (t.cyclic) {
  703. let totalSize: number = (t._sizeType ? t._thisNodeUt.height : t._thisNodeUt.width);
  704. t._cyclicPos1 = 0;
  705. totalSize -= t._cyclicPos1;
  706. t._cyclicNum = Math.ceil(totalSize / t._allItemSizeNoEdge) + 1;
  707. let spacing: number = t._sizeType ? t._lineGap : t._columnGap;
  708. t._cyclicPos2 = t._cyclicPos1 + t._allItemSizeNoEdge + spacing;
  709. t._cyclicAllItemSize = t._allItemSize + (t._allItemSizeNoEdge * (t._cyclicNum - 1)) + (spacing * (t._cyclicNum - 1));
  710. t._cycilcAllItemSizeNoEdge = t._allItemSizeNoEdge * t._cyclicNum;
  711. t._cycilcAllItemSizeNoEdge += spacing * (t._cyclicNum - 1);
  712. // cc.log('_cyclicNum ->', t._cyclicNum, t._allItemSizeNoEdge, t._allItemSize, t._cyclicPos1, t._cyclicPos2);
  713. }
  714. t._lack = !t.cyclic && t._allItemSize < (t._sizeType ? t._thisNodeUt.height : t._thisNodeUt.width);
  715. let slideOffset: number = ((!t._lack || !t.lackCenter) && t.lackSlide) ? 0 : .1;
  716. let targetWH: number = t._lack ? ((t._sizeType ? t._thisNodeUt.height : t._thisNodeUt.width) - slideOffset) : (t.cyclic ? t._cyclicAllItemSize : t._allItemSize);
  717. if (targetWH < 0)
  718. targetWH = 0;
  719. if (t._sizeType) {
  720. t._contentUt.height = targetWH;
  721. } else {
  722. t._contentUt.width = targetWH;
  723. }
  724. // cc.log('_resizeContent() numItems =', t._numItems, ',content =', t.content);
  725. }
  726. //滚动进行时...
  727. _onScrolling(ev: Event = null) {
  728. if (this.frameCount == null)
  729. this.frameCount = this._updateRate;
  730. if (!this._forceUpdate && (ev && ev.type != 'scroll-ended') && this.frameCount > 0) {
  731. this.frameCount--;
  732. return;
  733. } else
  734. this.frameCount = this._updateRate;
  735. if (this._aniDelRuning)
  736. return;
  737. //循环列表处理
  738. if (this.cyclic) {
  739. let scrollPos: any = this.content.getPosition();
  740. scrollPos = this._sizeType ? scrollPos.y : scrollPos.x;
  741. let addVal = this._allItemSizeNoEdge + (this._sizeType ? this._lineGap : this._columnGap);
  742. let add: any = this._sizeType ? new Vec3(0, addVal, 0) : new Vec3(addVal, 0, 0);
  743. let contentPos = this.content.getPosition();
  744. switch (this._alignCalcType) {
  745. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  746. if (scrollPos > -this._cyclicPos1) {
  747. contentPos.set(-this._cyclicPos2, contentPos.y, contentPos.z);
  748. this.content.setPosition(contentPos);
  749. if (this._scrollView.isAutoScrolling()) {
  750. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].subtract(add);
  751. }
  752. // if (this._beganPos) {
  753. // this._beganPos += add;
  754. // }
  755. } else if (scrollPos < -this._cyclicPos2) {
  756. contentPos.set(-this._cyclicPos1, contentPos.y, contentPos.z);
  757. this.content.setPosition(contentPos);
  758. if (this._scrollView.isAutoScrolling()) {
  759. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].add(add);
  760. }
  761. // if (this._beganPos) {
  762. // this._beganPos -= add;
  763. // }
  764. }
  765. break;
  766. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  767. if (scrollPos < this._cyclicPos1) {
  768. contentPos.set(this._cyclicPos2, contentPos.y, contentPos.z);
  769. this.content.setPosition(contentPos);
  770. if (this._scrollView.isAutoScrolling()) {
  771. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].add(add);
  772. }
  773. } else if (scrollPos > this._cyclicPos2) {
  774. contentPos.set(this._cyclicPos1, contentPos.y, contentPos.z);
  775. this.content.setPosition(contentPos);
  776. if (this._scrollView.isAutoScrolling()) {
  777. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].subtract(add);
  778. }
  779. }
  780. break;
  781. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  782. if (scrollPos < this._cyclicPos1) {
  783. contentPos.set(contentPos.x, this._cyclicPos2, contentPos.z);
  784. this.content.setPosition(contentPos);
  785. if (this._scrollView.isAutoScrolling()) {
  786. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].add(add);
  787. }
  788. } else if (scrollPos > this._cyclicPos2) {
  789. contentPos.set(contentPos.x, this._cyclicPos1, contentPos.z);
  790. this.content.setPosition(contentPos);
  791. if (this._scrollView.isAutoScrolling()) {
  792. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].subtract(add);
  793. }
  794. }
  795. break;
  796. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  797. if (scrollPos > -this._cyclicPos1) {
  798. contentPos.set(contentPos.x, -this._cyclicPos2, contentPos.z);
  799. this.content.setPosition(contentPos);
  800. if (this._scrollView.isAutoScrolling()) {
  801. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].subtract(add);
  802. }
  803. } else if (scrollPos < -this._cyclicPos2) {
  804. contentPos.set(contentPos.x, -this._cyclicPos1, contentPos.z);
  805. this.content.setPosition(contentPos);
  806. if (this._scrollView.isAutoScrolling()) {
  807. this._scrollView['_autoScrollStartPosition'] = this._scrollView['_autoScrollStartPosition'].add(add);
  808. }
  809. }
  810. break;
  811. }
  812. }
  813. this._calcViewPos();
  814. let vTop: number, vRight: number, vBottom: number, vLeft: number;
  815. if (this._sizeType) {
  816. vTop = this.viewTop;
  817. vBottom = this.viewBottom;
  818. } else {
  819. vRight = this.viewRight;
  820. vLeft = this.viewLeft;
  821. }
  822. if (this._virtual) {
  823. this.displayData = [];
  824. let itemPos: any;
  825. let curId: number = 0;
  826. let endId: number = this._numItems - 1;
  827. if (this._customSize) {
  828. let breakFor: boolean = false;
  829. //如果该item的位置在可视区域内,就推入displayData
  830. for (; curId <= endId && !breakFor; curId++) {
  831. itemPos = this._calcItemPos(curId);
  832. switch (this._align) {
  833. case Layout.Type.HORIZONTAL:
  834. if (itemPos.right >= vLeft && itemPos.left <= vRight) {
  835. this.displayData.push(itemPos);
  836. } else if (curId != 0 && this.displayData.length > 0) {
  837. breakFor = true;
  838. }
  839. break;
  840. case Layout.Type.VERTICAL:
  841. if (itemPos.bottom <= vTop && itemPos.top >= vBottom) {
  842. this.displayData.push(itemPos);
  843. } else if (curId != 0 && this.displayData.length > 0) {
  844. breakFor = true;
  845. }
  846. break;
  847. case Layout.Type.GRID:
  848. switch (this._startAxis) {
  849. case Layout.AxisDirection.HORIZONTAL:
  850. if (itemPos.bottom <= vTop && itemPos.top >= vBottom) {
  851. this.displayData.push(itemPos);
  852. } else if (curId != 0 && this.displayData.length > 0) {
  853. breakFor = true;
  854. }
  855. break;
  856. case Layout.AxisDirection.VERTICAL:
  857. if (itemPos.right >= vLeft && itemPos.left <= vRight) {
  858. this.displayData.push(itemPos);
  859. } else if (curId != 0 && this.displayData.length > 0) {
  860. breakFor = true;
  861. }
  862. break;
  863. }
  864. break;
  865. }
  866. }
  867. } else {
  868. let ww: number = this._itemSize.width + this._columnGap;
  869. let hh: number = this._itemSize.height + this._lineGap;
  870. switch (this._alignCalcType) {
  871. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  872. curId = (vLeft - this._leftGap) / ww;
  873. endId = (vRight - this._leftGap) / ww;
  874. break;
  875. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  876. curId = (-vRight - this._rightGap) / ww;
  877. endId = (-vLeft - this._rightGap) / ww;
  878. break;
  879. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  880. curId = (-vTop - this._topGap) / hh;
  881. endId = (-vBottom - this._topGap) / hh;
  882. break;
  883. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  884. curId = (vBottom - this._bottomGap) / hh;
  885. endId = (vTop - this._bottomGap) / hh;
  886. break;
  887. }
  888. curId = Math.floor(curId) * this._colLineNum;
  889. endId = Math.ceil(endId) * this._colLineNum;
  890. endId--;
  891. if (curId < 0)
  892. curId = 0;
  893. if (endId >= this._numItems)
  894. endId = this._numItems - 1;
  895. for (; curId <= endId; curId++) {
  896. this.displayData.push(this._calcItemPos(curId));
  897. }
  898. }
  899. this._delRedundantItem();
  900. if (this.displayData.length <= 0 || !this._numItems) { //if none, delete all.
  901. this._lastDisplayData = [];
  902. return;
  903. }
  904. this.firstListId = this.displayData[0].id;
  905. this.displayItemNum = this.displayData.length;
  906. let len: number = this._lastDisplayData.length;
  907. let haveDataChange: boolean = this.displayItemNum != len;
  908. if (haveDataChange) {
  909. // 如果是逐帧渲染,需要排序
  910. if (this.frameByFrameRenderNum > 0) {
  911. this._lastDisplayData.sort((a, b) => { return a - b });
  912. }
  913. // 因List的显示数据是有序的,所以只需要判断数组长度是否相等,以及头、尾两个元素是否相等即可。
  914. haveDataChange = this.firstListId != this._lastDisplayData[0] || this.displayData[this.displayItemNum - 1].id != this._lastDisplayData[len - 1];
  915. }
  916. if (this._forceUpdate || haveDataChange) { //如果是强制更新
  917. if (this.frameByFrameRenderNum > 0) {
  918. // if (this._updateDone) {
  919. // this._lastDisplayData = [];
  920. //逐帧渲染
  921. if (this._numItems > 0) {
  922. if (!this._updateDone) {
  923. this._doneAfterUpdate = true;
  924. } else {
  925. this._updateCounter = 0;
  926. }
  927. this._updateDone = false;
  928. } else {
  929. this._updateCounter = 0;
  930. this._updateDone = true;
  931. }
  932. // }
  933. } else {
  934. //直接渲染
  935. this._lastDisplayData = [];
  936. // cc.log('List Display Data II::', this.displayData);
  937. for (let c = 0; c < this.displayItemNum; c++) {
  938. this._createOrUpdateItem(this.displayData[c]);
  939. }
  940. this._forceUpdate = false;
  941. }
  942. }
  943. this._calcNearestItem();
  944. }
  945. }
  946. //计算可视范围
  947. _calcViewPos() {
  948. let scrollPos: any = this.content.getPosition();
  949. switch (this._alignCalcType) {
  950. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  951. this.elasticLeft = scrollPos.x > 0 ? scrollPos.x : 0;
  952. this.viewLeft = (scrollPos.x < 0 ? -scrollPos.x : 0) - this.elasticLeft;
  953. this.viewRight = this.viewLeft + this._thisNodeUt.width;
  954. this.elasticRight = this.viewRight > this._contentUt.width ? Math.abs(this.viewRight - this._contentUt.width) : 0;
  955. this.viewRight += this.elasticRight;
  956. // cc.log(this.elasticLeft, this.elasticRight, this.viewLeft, this.viewRight);
  957. break;
  958. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  959. this.elasticRight = scrollPos.x < 0 ? -scrollPos.x : 0;
  960. this.viewRight = (scrollPos.x > 0 ? -scrollPos.x : 0) + this.elasticRight;
  961. this.viewLeft = this.viewRight - this._thisNodeUt.width;
  962. this.elasticLeft = this.viewLeft < -this._contentUt.width ? Math.abs(this.viewLeft + this._contentUt.width) : 0;
  963. this.viewLeft -= this.elasticLeft;
  964. // cc.log(this.elasticLeft, this.elasticRight, this.viewLeft, this.viewRight);
  965. break;
  966. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  967. this.elasticTop = scrollPos.y < 0 ? Math.abs(scrollPos.y) : 0;
  968. this.viewTop = (scrollPos.y > 0 ? -scrollPos.y : 0) + this.elasticTop;
  969. this.viewBottom = this.viewTop - this._thisNodeUt.height;
  970. this.elasticBottom = this.viewBottom < -this._contentUt.height ? Math.abs(this.viewBottom + this._contentUt.height) : 0;
  971. this.viewBottom += this.elasticBottom;
  972. // cc.log(this.elasticTop, this.elasticBottom, this.viewTop, this.viewBottom);
  973. break;
  974. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  975. this.elasticBottom = scrollPos.y > 0 ? Math.abs(scrollPos.y) : 0;
  976. this.viewBottom = (scrollPos.y < 0 ? -scrollPos.y : 0) - this.elasticBottom;
  977. this.viewTop = this.viewBottom + this._thisNodeUt.height;
  978. this.elasticTop = this.viewTop > this._contentUt.height ? Math.abs(this.viewTop - this._contentUt.height) : 0;
  979. this.viewTop -= this.elasticTop;
  980. // cc.log(this.elasticTop, this.elasticBottom, this.viewTop, this.viewBottom);
  981. break;
  982. }
  983. }
  984. //计算位置 根据id
  985. _calcItemPos(id: number) {
  986. let width: number, height: number, top: number, bottom: number, left: number, right: number, itemX: number, itemY: number;
  987. switch (this._align) {
  988. case Layout.Type.HORIZONTAL:
  989. switch (this._horizontalDir) {
  990. case Layout.HorizontalDirection.LEFT_TO_RIGHT: {
  991. if (this._customSize) {
  992. let fixed: any = this._getFixedSize(id);
  993. left = this._leftGap + ((this._itemSize.width + this._columnGap) * (id - fixed.count)) + (fixed.val + (this._columnGap * fixed.count));
  994. let cs: number = this._customSize[id];
  995. width = (cs > 0 ? cs : this._itemSize.width);
  996. } else {
  997. left = this._leftGap + ((this._itemSize.width + this._columnGap) * id);
  998. width = this._itemSize.width;
  999. }
  1000. if (this.lackCenter) {
  1001. left -= this._leftGap;
  1002. let offset: number = (this._contentUt.width / 2) - (this._allItemSizeNoEdge / 2);
  1003. left += offset;
  1004. }
  1005. right = left + width;
  1006. return {
  1007. id: id,
  1008. left: left,
  1009. right: right,
  1010. x: left + (this._itemTmpUt.anchorX * width),
  1011. y: this._itemTmp.y,
  1012. };
  1013. }
  1014. case Layout.HorizontalDirection.RIGHT_TO_LEFT: {
  1015. if (this._customSize) {
  1016. let fixed: any = this._getFixedSize(id);
  1017. right = -this._rightGap - ((this._itemSize.width + this._columnGap) * (id - fixed.count)) - (fixed.val + (this._columnGap * fixed.count));
  1018. let cs: number = this._customSize[id];
  1019. width = (cs > 0 ? cs : this._itemSize.width);
  1020. } else {
  1021. right = -this._rightGap - ((this._itemSize.width + this._columnGap) * id);
  1022. width = this._itemSize.width;
  1023. }
  1024. if (this.lackCenter) {
  1025. right += this._rightGap;
  1026. let offset: number = (this._contentUt.width / 2) - (this._allItemSizeNoEdge / 2);
  1027. right -= offset;
  1028. }
  1029. left = right - width;
  1030. return {
  1031. id: id,
  1032. right: right,
  1033. left: left,
  1034. x: left + (this._itemTmpUt.anchorX * width),
  1035. y: this._itemTmp.y,
  1036. };
  1037. }
  1038. }
  1039. break;
  1040. case Layout.Type.VERTICAL: {
  1041. switch (this._verticalDir) {
  1042. case Layout.VerticalDirection.TOP_TO_BOTTOM: {
  1043. if (this._customSize) {
  1044. let fixed: any = this._getFixedSize(id);
  1045. top = -this._topGap - ((this._itemSize.height + this._lineGap) * (id - fixed.count)) - (fixed.val + (this._lineGap * fixed.count));
  1046. let cs: number = this._customSize[id];
  1047. height = (cs > 0 ? cs : this._itemSize.height);
  1048. } else {
  1049. top = -this._topGap - ((this._itemSize.height + this._lineGap) * id);
  1050. height = this._itemSize.height;
  1051. }
  1052. if (this.lackCenter) {
  1053. top += this._topGap;
  1054. let offset: number = (this._contentUt.height / 2) - (this._allItemSizeNoEdge / 2);
  1055. top -= offset;
  1056. }
  1057. bottom = top - height;
  1058. return {
  1059. id: id,
  1060. top: top,
  1061. bottom: bottom,
  1062. x: this._itemTmp.x,
  1063. y: bottom + (this._itemTmpUt.anchorY * height),
  1064. };
  1065. }
  1066. case Layout.VerticalDirection.BOTTOM_TO_TOP: {
  1067. if (this._customSize) {
  1068. let fixed: any = this._getFixedSize(id);
  1069. bottom = this._bottomGap + ((this._itemSize.height + this._lineGap) * (id - fixed.count)) + (fixed.val + (this._lineGap * fixed.count));
  1070. let cs: number = this._customSize[id];
  1071. height = (cs > 0 ? cs : this._itemSize.height);
  1072. } else {
  1073. bottom = this._bottomGap + ((this._itemSize.height + this._lineGap) * id);
  1074. height = this._itemSize.height;
  1075. }
  1076. if (this.lackCenter) {
  1077. bottom -= this._bottomGap;
  1078. let offset: number = (this._contentUt.height / 2) - (this._allItemSizeNoEdge / 2);
  1079. bottom += offset;
  1080. }
  1081. top = bottom + height;
  1082. return {
  1083. id: id,
  1084. top: top,
  1085. bottom: bottom,
  1086. x: this._itemTmp.x,
  1087. y: bottom + (this._itemTmpUt.anchorY * height),
  1088. };
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. case Layout.Type.GRID: {
  1094. let colLine: number = Math.floor(id / this._colLineNum);
  1095. switch (this._startAxis) {
  1096. case Layout.AxisDirection.HORIZONTAL: {
  1097. switch (this._verticalDir) {
  1098. case Layout.VerticalDirection.TOP_TO_BOTTOM: {
  1099. top = -this._topGap - ((this._itemSize.height + this._lineGap) * colLine);
  1100. bottom = top - this._itemSize.height;
  1101. itemY = bottom + (this._itemTmpUt.anchorY * this._itemSize.height);
  1102. break;
  1103. }
  1104. case Layout.VerticalDirection.BOTTOM_TO_TOP: {
  1105. bottom = this._bottomGap + ((this._itemSize.height + this._lineGap) * colLine);
  1106. top = bottom + this._itemSize.height;
  1107. itemY = bottom + (this._itemTmpUt.anchorY * this._itemSize.height);
  1108. break;
  1109. }
  1110. }
  1111. itemX = this._leftGap + ((id % this._colLineNum) * (this._itemSize.width + this._columnGap));
  1112. switch (this._horizontalDir) {
  1113. case Layout.HorizontalDirection.LEFT_TO_RIGHT: {
  1114. itemX += (this._itemTmpUt.anchorX * this._itemSize.width);
  1115. itemX -= (this._contentUt.anchorX * this._contentUt.width);
  1116. break;
  1117. }
  1118. case Layout.HorizontalDirection.RIGHT_TO_LEFT: {
  1119. itemX += ((1 - this._itemTmpUt.anchorX) * this._itemSize.width);
  1120. itemX -= ((1 - this._contentUt.anchorX) * this._contentUt.width);
  1121. itemX *= -1;
  1122. break;
  1123. }
  1124. }
  1125. return {
  1126. id: id,
  1127. top: top,
  1128. bottom: bottom,
  1129. x: itemX,
  1130. y: itemY,
  1131. };
  1132. }
  1133. case Layout.AxisDirection.VERTICAL: {
  1134. switch (this._horizontalDir) {
  1135. case Layout.HorizontalDirection.LEFT_TO_RIGHT: {
  1136. left = this._leftGap + ((this._itemSize.width + this._columnGap) * colLine);
  1137. right = left + this._itemSize.width;
  1138. itemX = left + (this._itemTmpUt.anchorX * this._itemSize.width);
  1139. itemX -= (this._contentUt.anchorX * this._contentUt.width);
  1140. break;
  1141. }
  1142. case Layout.HorizontalDirection.RIGHT_TO_LEFT: {
  1143. right = -this._rightGap - ((this._itemSize.width + this._columnGap) * colLine);
  1144. left = right - this._itemSize.width;
  1145. itemX = left + (this._itemTmpUt.anchorX * this._itemSize.width);
  1146. itemX += ((1 - this._contentUt.anchorX) * this._contentUt.width);
  1147. break;
  1148. }
  1149. }
  1150. itemY = -this._topGap - ((id % this._colLineNum) * (this._itemSize.height + this._lineGap));
  1151. switch (this._verticalDir) {
  1152. case Layout.VerticalDirection.TOP_TO_BOTTOM: {
  1153. itemY -= ((1 - this._itemTmpUt.anchorY) * this._itemSize.height);
  1154. itemY += ((1 - this._contentUt.anchorY) * this._contentUt.height);
  1155. break;
  1156. }
  1157. case Layout.VerticalDirection.BOTTOM_TO_TOP: {
  1158. itemY -= ((this._itemTmpUt.anchorY) * this._itemSize.height);
  1159. itemY += (this._contentUt.anchorY * this._contentUt.height);
  1160. itemY *= -1;
  1161. break;
  1162. }
  1163. }
  1164. return {
  1165. id: id,
  1166. left: left,
  1167. right: right,
  1168. x: itemX,
  1169. y: itemY,
  1170. };
  1171. }
  1172. }
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. //计算已存在的Item的位置
  1178. _calcExistItemPos(id: number) {
  1179. let item: any = this.getItemByListId(id);
  1180. if (!item)
  1181. return null;
  1182. let ut: UITransform = item.getComponent(UITransform);
  1183. let pos: Vec3 = item.getPosition();
  1184. let data: any = {
  1185. id: id,
  1186. x: pos.x,
  1187. y: pos.y,
  1188. }
  1189. if (this._sizeType) {
  1190. data.top = pos.y + (ut.height * (1 - ut.anchorY));
  1191. data.bottom = pos.y - (ut.height * ut.anchorY);
  1192. } else {
  1193. data.left = pos.x - (ut.width * ut.anchorX);
  1194. data.right = pos.x + (ut.width * (1 - ut.anchorX));
  1195. }
  1196. return data;
  1197. }
  1198. //获取Item位置
  1199. getItemPos(id: number) {
  1200. if (this._virtual)
  1201. return this._calcItemPos(id);
  1202. else {
  1203. if (this.frameByFrameRenderNum)
  1204. return this._calcItemPos(id);
  1205. else
  1206. return this._calcExistItemPos(id);
  1207. }
  1208. }
  1209. //获取固定尺寸
  1210. _getFixedSize(listId: number) {
  1211. if (!this._customSize)
  1212. return null;
  1213. if (listId == null)
  1214. listId = this._numItems;
  1215. let fixed: number = 0;
  1216. let count: number = 0;
  1217. for (let id in this._customSize) {
  1218. if (parseInt(id) < listId) {
  1219. fixed += this._customSize[id];
  1220. count++;
  1221. }
  1222. }
  1223. return {
  1224. val: fixed,
  1225. count: count,
  1226. }
  1227. }
  1228. //滚动结束时..
  1229. _onScrollBegan() {
  1230. this._beganPos = this._sizeType ? this.viewTop : this.viewLeft;
  1231. }
  1232. //滚动结束时..
  1233. _onScrollEnded() {
  1234. let t: any = this;
  1235. t._curScrollIsTouch = false;
  1236. if (t.scrollToListId != null) {
  1237. let item: any = t.getItemByListId(t.scrollToListId);
  1238. t.scrollToListId = null;
  1239. if (item) {
  1240. tween(item)
  1241. .to(.1, { scale: 1.06 })
  1242. .to(.1, { scale: 1 })
  1243. .start();
  1244. }
  1245. }
  1246. t._onScrolling();
  1247. if (t._slideMode == SlideType.ADHERING &&
  1248. !t.adhering
  1249. ) {
  1250. //cc.log(t.adhering, t._scrollView.isAutoScrolling(), t._scrollView.isScrolling());
  1251. t.adhere();
  1252. } else if (t._slideMode == SlideType.PAGE) {
  1253. if (t._beganPos != null && t._curScrollIsTouch) {
  1254. this._pageAdhere();
  1255. } else {
  1256. t.adhere();
  1257. }
  1258. }
  1259. }
  1260. // 触摸时
  1261. _onTouchStart(ev, captureListeners) {
  1262. if (this._scrollView['_hasNestedViewGroup'](ev, captureListeners))
  1263. return;
  1264. this._curScrollIsTouch = true;
  1265. let isMe = ev.eventPhase === Event.AT_TARGET && ev.target === this.node;
  1266. if (!isMe) {
  1267. let itemNode: any = ev.target;
  1268. while (itemNode._listId == null && itemNode.parent)
  1269. itemNode = itemNode.parent;
  1270. this._scrollItem = itemNode._listId != null ? itemNode : ev.target;
  1271. }
  1272. }
  1273. //触摸抬起时..
  1274. _onTouchUp() {
  1275. let t: any = this;
  1276. t._scrollPos = null;
  1277. if (t._slideMode == SlideType.ADHERING) {
  1278. if (this.adhering)
  1279. this._adheringBarrier = true;
  1280. t.adhere();
  1281. } else if (t._slideMode == SlideType.PAGE) {
  1282. if (t._beganPos != null) {
  1283. this._pageAdhere();
  1284. } else {
  1285. t.adhere();
  1286. }
  1287. }
  1288. this._scrollItem = null;
  1289. }
  1290. _onTouchCancelled(ev, captureListeners) {
  1291. let t = this;
  1292. if (t._scrollView['_hasNestedViewGroup'](ev, captureListeners) || ev.simulate)
  1293. return;
  1294. t._scrollPos = null;
  1295. if (t._slideMode == SlideType.ADHERING) {
  1296. if (t.adhering)
  1297. t._adheringBarrier = true;
  1298. t.adhere();
  1299. } else if (t._slideMode == SlideType.PAGE) {
  1300. if (t._beganPos != null) {
  1301. t._pageAdhere();
  1302. } else {
  1303. t.adhere();
  1304. }
  1305. }
  1306. this._scrollItem = null;
  1307. }
  1308. //当尺寸改变
  1309. _onSizeChanged() {
  1310. if (this.checkInited(false))
  1311. this._onScrolling();
  1312. }
  1313. //当Item自适应
  1314. _onItemAdaptive(item: any) {
  1315. let ut: UITransform = item.getComponent(UITransform);
  1316. // if (this.checkInited(false)) {
  1317. if (
  1318. (!this._sizeType && ut.width != this._itemSize.width)
  1319. || (this._sizeType && ut.height != this._itemSize.height)
  1320. ) {
  1321. if (!this._customSize)
  1322. this._customSize = {};
  1323. let val = this._sizeType ? ut.height : ut.width;
  1324. if (this._customSize[item._listId] != val) {
  1325. this._customSize[item._listId] = val;
  1326. this._resizeContent();
  1327. // this.content.children.forEach((child: Node) => {
  1328. // this._updateItemPos(child);
  1329. // });
  1330. this.updateAll();
  1331. // 如果当前正在运行 scrollTo,肯定会不准确,在这里做修正
  1332. if (this._scrollToListId != null) {
  1333. this._scrollPos = null;
  1334. this.unschedule(this._scrollToSo);
  1335. this.scrollTo(this._scrollToListId, Math.max(0, this._scrollToEndTime - ((new Date()).getTime() / 1000)));
  1336. }
  1337. }
  1338. }
  1339. // }
  1340. }
  1341. //PAGE粘附
  1342. _pageAdhere() {
  1343. let t = this;
  1344. if (!t.cyclic && (t.elasticTop > 0 || t.elasticRight > 0 || t.elasticBottom > 0 || t.elasticLeft > 0))
  1345. return;
  1346. let curPos = t._sizeType ? t.viewTop : t.viewLeft;
  1347. let dis = (t._sizeType ? t._thisNodeUt.height : t._thisNodeUt.width) * t.pageDistance;
  1348. let canSkip = Math.abs(t._beganPos - curPos) > dis;
  1349. if (canSkip) {
  1350. let timeInSecond = .5;
  1351. switch (t._alignCalcType) {
  1352. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  1353. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  1354. if (t._beganPos > curPos) {
  1355. t.prePage(timeInSecond);
  1356. // cc.log('_pageAdhere PPPPPPPPPPPPPPP');
  1357. } else {
  1358. t.nextPage(timeInSecond);
  1359. // cc.log('_pageAdhere NNNNNNNNNNNNNNN');
  1360. }
  1361. break;
  1362. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  1363. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  1364. if (t._beganPos < curPos) {
  1365. t.prePage(timeInSecond);
  1366. } else {
  1367. t.nextPage(timeInSecond);
  1368. }
  1369. break;
  1370. }
  1371. } else if (t.elasticTop <= 0 && t.elasticRight <= 0 && t.elasticBottom <= 0 && t.elasticLeft <= 0) {
  1372. t.adhere();
  1373. }
  1374. t._beganPos = null;
  1375. }
  1376. //粘附
  1377. adhere() {
  1378. let t: any = this;
  1379. if (!t.checkInited())
  1380. return;
  1381. if (t.elasticTop > 0 || t.elasticRight > 0 || t.elasticBottom > 0 || t.elasticLeft > 0)
  1382. return;
  1383. t.adhering = true;
  1384. t._calcNearestItem();
  1385. let offset: number = (t._sizeType ? t._topGap : t._leftGap) / (t._sizeType ? t._thisNodeUt.height : t._thisNodeUt.width);
  1386. let timeInSecond: number = .7;
  1387. t.scrollTo(t.nearestListId, timeInSecond, offset);
  1388. }
  1389. //Update..
  1390. update() {
  1391. if (this.frameByFrameRenderNum <= 0 || this._updateDone)
  1392. return;
  1393. // cc.log(this.displayData.length, this._updateCounter, this.displayData[this._updateCounter]);
  1394. if (this._virtual) {
  1395. let len: number = (this._updateCounter + this.frameByFrameRenderNum) > this.displayItemNum ? this.displayItemNum : (this._updateCounter + this.frameByFrameRenderNum);
  1396. for (let n: number = this._updateCounter; n < len; n++) {
  1397. let data: any = this.displayData[n];
  1398. if (data) {
  1399. this._createOrUpdateItem(data);
  1400. }
  1401. }
  1402. if (this._updateCounter >= this.displayItemNum - 1) { //最后一个
  1403. if (this._doneAfterUpdate) {
  1404. this._updateCounter = 0;
  1405. this._updateDone = false;
  1406. // if (!this._scrollView.isScrolling())
  1407. this._doneAfterUpdate = false;
  1408. } else {
  1409. this._updateDone = true;
  1410. this._delRedundantItem();
  1411. this._forceUpdate = false;
  1412. this._calcNearestItem();
  1413. if (this.slideMode == SlideType.PAGE)
  1414. this.curPageNum = this.nearestListId;
  1415. }
  1416. } else {
  1417. this._updateCounter += this.frameByFrameRenderNum;
  1418. }
  1419. } else {
  1420. if (this._updateCounter < this._numItems) {
  1421. let len: number = (this._updateCounter + this.frameByFrameRenderNum) > this._numItems ? this._numItems : (this._updateCounter + this.frameByFrameRenderNum);
  1422. for (let n: number = this._updateCounter; n < len; n++) {
  1423. this._createOrUpdateItem2(n);
  1424. }
  1425. this._updateCounter += this.frameByFrameRenderNum;
  1426. } else {
  1427. this._updateDone = true;
  1428. this._calcNearestItem();
  1429. if (this.slideMode == SlideType.PAGE)
  1430. this.curPageNum = this.nearestListId;
  1431. }
  1432. }
  1433. }
  1434. /**
  1435. * 创建或更新Item(虚拟列表用)
  1436. * @param {Object} data 数据
  1437. */
  1438. _createOrUpdateItem(data: any) {
  1439. let item: any = this.getItemByListId(data.id);
  1440. if (!item) { //如果不存在
  1441. let canGet: boolean = this._pool.size() > 0;
  1442. if (canGet) {
  1443. item = this._pool.get();
  1444. // cc.log('从池中取出:: 旧id =', item['_listId'], ',新id =', data.id, item);
  1445. } else {
  1446. item = instantiate(this._itemTmp);
  1447. // cc.log('新建::', data.id, item);
  1448. }
  1449. if (!canGet || !isValid(item)) {
  1450. item = instantiate(this._itemTmp);
  1451. canGet = false;
  1452. }
  1453. if (item._listId != data.id) {
  1454. item._listId = data.id;
  1455. let ut: UITransform = item.getComponent(UITransform);
  1456. ut.setContentSize(this._itemSize);
  1457. }
  1458. item.setPosition(new Vec3(data.x, data.y, 0));
  1459. this._resetItemSize(item);
  1460. this.content.addChild(item);
  1461. if (canGet && this._needUpdateWidget) {
  1462. let widget: Widget = item.getComponent(Widget);
  1463. if (widget)
  1464. widget.updateAlignment();
  1465. }
  1466. item.setSiblingIndex(this.content.children.length - 1);
  1467. let listItem: ListItem = item.getComponent(ListItem);
  1468. item['listItem'] = listItem;
  1469. if (listItem) {
  1470. listItem.listId = data.id;
  1471. listItem.list = this;
  1472. listItem._registerEvent();
  1473. }
  1474. if (this.renderEvent) {
  1475. EventHandler.emitEvents([this.renderEvent], item, data.id % this._actualNumItems);
  1476. }
  1477. } else if (this._forceUpdate && this.renderEvent) { //强制更新
  1478. item.setPosition(new Vec3(data.x, data.y, 0));
  1479. this._resetItemSize(item);
  1480. // cc.log('ADD::', data.id, item);
  1481. if (this.renderEvent) {
  1482. EventHandler.emitEvents([this.renderEvent], item, data.id % this._actualNumItems);
  1483. }
  1484. }
  1485. this._resetItemSize(item);
  1486. this._updateListItem(item['listItem']);
  1487. if (this._lastDisplayData.indexOf(data.id) < 0) {
  1488. this._lastDisplayData.push(data.id);
  1489. }
  1490. }
  1491. //创建或更新Item(非虚拟列表用)
  1492. _createOrUpdateItem2(listId: number) {
  1493. let item: any = this.content.children[listId];
  1494. let listItem: ListItem;
  1495. if (!item) { //如果不存在
  1496. item = instantiate(this._itemTmp);
  1497. item._listId = listId;
  1498. this.content.addChild(item);
  1499. listItem = item.getComponent(ListItem);
  1500. item['listItem'] = listItem;
  1501. if (listItem) {
  1502. listItem.listId = listId;
  1503. listItem.list = this;
  1504. listItem._registerEvent();
  1505. }
  1506. if (this.renderEvent) {
  1507. EventHandler.emitEvents([this.renderEvent], item, listId % this._actualNumItems);
  1508. }
  1509. } else if (this._forceUpdate && this.renderEvent) { //强制更新
  1510. item._listId = listId;
  1511. if (listItem)
  1512. listItem.listId = listId;
  1513. if (this.renderEvent) {
  1514. EventHandler.emitEvents([this.renderEvent], item, listId % this._actualNumItems);
  1515. }
  1516. }
  1517. this._updateListItem(listItem);
  1518. if (this._lastDisplayData.indexOf(listId) < 0) {
  1519. this._lastDisplayData.push(listId);
  1520. }
  1521. }
  1522. _updateListItem(listItem: ListItem) {
  1523. if (!listItem)
  1524. return;
  1525. if (this.selectedMode > SelectedType.NONE) {
  1526. let item: any = listItem.node;
  1527. switch (this.selectedMode) {
  1528. case SelectedType.SINGLE:
  1529. listItem.selected = this.selectedId == item._listId;
  1530. break;
  1531. case SelectedType.MULT:
  1532. listItem.selected = this.multSelected.indexOf(item._listId) >= 0;
  1533. break;
  1534. }
  1535. }
  1536. }
  1537. //仅虚拟列表用
  1538. _resetItemSize(item: any) {
  1539. return;
  1540. let size: number;
  1541. let ut: UITransform = item.getComponent(UITransform);
  1542. if (this._customSize && this._customSize[item._listId]) {
  1543. size = this._customSize[item._listId];
  1544. } else {
  1545. if (this._colLineNum > 1)
  1546. ut.setContentSize(this._itemSize);
  1547. else
  1548. size = this._sizeType ? this._itemSize.height : this._itemSize.width;
  1549. }
  1550. if (size) {
  1551. if (this._sizeType)
  1552. ut.height = size;
  1553. else
  1554. ut.width = size;
  1555. }
  1556. }
  1557. /**
  1558. * 更新Item位置
  1559. * @param {Number||Node} listIdOrItem
  1560. */
  1561. _updateItemPos(listIdOrItem: any) {
  1562. let item: any = isNaN(listIdOrItem) ? listIdOrItem : this.getItemByListId(listIdOrItem);
  1563. let pos: any = this.getItemPos(item._listId);
  1564. item.setPosition(pos.x, pos.y);
  1565. }
  1566. /**
  1567. * 设置多选
  1568. * @param {Array} args 可以是单个listId,也可是个listId数组
  1569. * @param {Boolean} bool 值,如果为null的话,则直接用args覆盖
  1570. */
  1571. setMultSelected(args: any, bool: boolean) {
  1572. let t: any = this;
  1573. if (!t.checkInited())
  1574. return;
  1575. if (!Array.isArray(args)) {
  1576. args = [args];
  1577. }
  1578. if (bool == null) {
  1579. t.multSelected = args;
  1580. } else {
  1581. let listId: number, sub: number;
  1582. if (bool) {
  1583. for (let n: number = args.length - 1; n >= 0; n--) {
  1584. listId = args[n];
  1585. sub = t.multSelected.indexOf(listId);
  1586. if (sub < 0) {
  1587. t.multSelected.push(listId);
  1588. }
  1589. }
  1590. } else {
  1591. for (let n: number = args.length - 1; n >= 0; n--) {
  1592. listId = args[n];
  1593. sub = t.multSelected.indexOf(listId);
  1594. if (sub >= 0) {
  1595. t.multSelected.splice(sub, 1);
  1596. }
  1597. }
  1598. }
  1599. }
  1600. t._forceUpdate = true;
  1601. t._onScrolling();
  1602. }
  1603. /**
  1604. * 获取多选数据
  1605. * @returns
  1606. */
  1607. getMultSelected() {
  1608. return this.multSelected;
  1609. }
  1610. /**
  1611. * 多选是否有选择
  1612. * @param {number} listId 索引
  1613. * @returns
  1614. */
  1615. hasMultSelected(listId: number) {
  1616. return this.multSelected && this.multSelected.indexOf(listId) >= 0;
  1617. }
  1618. /**
  1619. * 更新指定的Item
  1620. * @param {Array} args 单个listId,或者数组
  1621. * @returns
  1622. */
  1623. updateItem(args: any) {
  1624. if (!this.checkInited())
  1625. return;
  1626. if (!Array.isArray(args)) {
  1627. args = [args];
  1628. }
  1629. for (let n: number = 0, len: number = args.length; n < len; n++) {
  1630. let listId: number = args[n];
  1631. let item: any = this.getItemByListId(listId);
  1632. if (item)
  1633. EventHandler.emitEvents([this.renderEvent], item, listId % this._actualNumItems);
  1634. }
  1635. }
  1636. /**
  1637. * 更新全部
  1638. */
  1639. updateAll() {
  1640. if (!this.checkInited())
  1641. return;
  1642. this.numItems = this.numItems;
  1643. }
  1644. /**
  1645. * 根据ListID获取Item
  1646. * @param {Number} listId
  1647. * @returns
  1648. */
  1649. getItemByListId(listId: number) {
  1650. if (this.content) {
  1651. for (let n: number = this.content.children.length - 1; n >= 0; n--) {
  1652. let item: any = this.content.children[n];
  1653. if (item._listId == listId)
  1654. return item;
  1655. }
  1656. }
  1657. }
  1658. /**
  1659. * 获取在显示区域外的Item
  1660. * @returns
  1661. */
  1662. _getOutsideItem() {
  1663. let item: any;
  1664. let result: any[] = [];
  1665. for (let n: number = this.content.children.length - 1; n >= 0; n--) {
  1666. item = this.content.children[n];
  1667. if (!this.displayData.find(d => d.id == item._listId)) {
  1668. result.push(item);
  1669. }
  1670. }
  1671. return result;
  1672. }
  1673. //删除显示区域以外的Item
  1674. _delRedundantItem() {
  1675. if (this._virtual) {
  1676. let arr: any[] = this._getOutsideItem();
  1677. for (let n: number = arr.length - 1; n >= 0; n--) {
  1678. let item: any = arr[n];
  1679. if (this._scrollItem && item._listId == this._scrollItem._listId)
  1680. continue;
  1681. item.isCached = true;
  1682. this._pool.put(item);
  1683. for (let m: number = this._lastDisplayData.length - 1; m >= 0; m--) {
  1684. if (this._lastDisplayData[m] == item._listId) {
  1685. this._lastDisplayData.splice(m, 1);
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. // cc.log('存入::', str, ' pool.length =', this._pool.length);
  1691. } else {
  1692. while (this.content.children.length > this._numItems) {
  1693. this._delSingleItem(this.content.children[this.content.children.length - 1]);
  1694. }
  1695. }
  1696. }
  1697. //删除单个Item
  1698. _delSingleItem(item: any) {
  1699. // cc.log('DEL::', item['_listId'], item);
  1700. item.removeFromParent();
  1701. if (item.destroy)
  1702. item.destroy();
  1703. item = null;
  1704. }
  1705. /**
  1706. * 动效删除Item(此方法只适用于虚拟列表,即_virtual=true)
  1707. * 一定要在回调函数里重新设置新的numItems进行刷新,毕竟本List是靠数据驱动的。
  1708. */
  1709. aniDelItem(listId: number, callFunc: Function, aniType: number) {
  1710. let t: any = this;
  1711. if (!t.checkInited() || t.cyclic || !t._virtual)
  1712. return console.error('This function is not allowed to be called!');
  1713. if (!callFunc)
  1714. return console.error('CallFunc are not allowed to be NULL, You need to delete the corresponding index in the data array in the CallFunc!');
  1715. if (t._aniDelRuning)
  1716. return console.warn('Please wait for the current deletion to finish!');
  1717. let item: any = t.getItemByListId(listId);
  1718. let listItem: ListItem;
  1719. if (!item) {
  1720. callFunc(listId);
  1721. return;
  1722. } else {
  1723. listItem = item.getComponent(ListItem);
  1724. }
  1725. t._aniDelRuning = true;
  1726. t._aniDelCB = callFunc;
  1727. t._aniDelItem = item;
  1728. t._aniDelBeforePos = item.position;
  1729. t._aniDelBeforeScale = item.scale;
  1730. let curLastId: number = t.displayData[t.displayData.length - 1].id;
  1731. let resetSelectedId: boolean = listItem.selected;
  1732. listItem.showAni(aniType, () => {
  1733. //判断有没有下一个,如果有的话,创建粗来
  1734. let newId: number;
  1735. if (curLastId < t._numItems - 2) {
  1736. newId = curLastId + 1;
  1737. }
  1738. if (newId != null) {
  1739. let newData: any = t._calcItemPos(newId);
  1740. t.displayData.push(newData);
  1741. if (t._virtual)
  1742. t._createOrUpdateItem(newData);
  1743. else
  1744. t._createOrUpdateItem2(newId);
  1745. } else
  1746. t._numItems--;
  1747. if (t.selectedMode == SelectedType.SINGLE) {
  1748. if (resetSelectedId) {
  1749. t._selectedId = -1;
  1750. } else if (t._selectedId - 1 >= 0) {
  1751. t._selectedId--;
  1752. }
  1753. } else if (t.selectedMode == SelectedType.MULT && t.multSelected.length) {
  1754. let sub: number = t.multSelected.indexOf(listId);
  1755. if (sub >= 0) {
  1756. t.multSelected.splice(sub, 1);
  1757. }
  1758. //多选的数据,在其后的全部减一
  1759. for (let n: number = t.multSelected.length - 1; n >= 0; n--) {
  1760. let id: number = t.multSelected[n];
  1761. if (id >= listId)
  1762. t.multSelected[n]--;
  1763. }
  1764. }
  1765. if (t._customSize) {
  1766. if (t._customSize[listId])
  1767. delete t._customSize[listId];
  1768. let newCustomSize: any = {};
  1769. let size: number;
  1770. for (let id in t._customSize) {
  1771. size = t._customSize[id];
  1772. let idNumber: number = parseInt(id);
  1773. newCustomSize[idNumber - (idNumber >= listId ? 1 : 0)] = size;
  1774. }
  1775. t._customSize = newCustomSize;
  1776. }
  1777. //后面的Item向前怼的动效
  1778. let sec: number = .2333;
  1779. let twe: Tween<Node>, haveCB: boolean;
  1780. for (let n: number = newId != null ? newId : curLastId; n >= listId + 1; n--) {
  1781. item = t.getItemByListId(n);
  1782. if (item) {
  1783. let posData: any = t._calcItemPos(n - 1);
  1784. twe = tween(item)
  1785. .to(sec, { position: new Vec3(posData.x, posData.y, 0) });
  1786. if (n <= listId + 1) {
  1787. haveCB = true;
  1788. twe.call(() => {
  1789. t._aniDelRuning = false;
  1790. callFunc(listId);
  1791. delete t._aniDelCB;
  1792. });
  1793. }
  1794. twe.start();
  1795. }
  1796. }
  1797. if (!haveCB) {
  1798. t._aniDelRuning = false;
  1799. callFunc(listId);
  1800. t._aniDelCB = null;
  1801. }
  1802. }, true);
  1803. }
  1804. /**
  1805. * 滚动到..
  1806. * @param {Number} listId 索引(如果<0,则滚到首个Item位置,如果>=_numItems,则滚到最末Item位置)
  1807. * @param {Number} timeInSecond 时间
  1808. * @param {Number} offset 索引目标位置偏移,0-1
  1809. * @param {Boolean} overStress 滚动后是否强调该Item(这只是个实验功能)
  1810. */
  1811. scrollTo(listId: number, timeInSecond: number = .5, offset: number = null, overStress: boolean = false) {
  1812. let t = this;
  1813. if (!t.checkInited(false))
  1814. return;
  1815. // t._scrollView.stopAutoScroll();
  1816. if (timeInSecond == null) //默认0.5
  1817. timeInSecond = .5;
  1818. else if (timeInSecond < 0)
  1819. timeInSecond = 0;
  1820. if (listId < 0)
  1821. listId = 0;
  1822. else if (listId >= t._numItems)
  1823. listId = t._numItems - 1;
  1824. // 以防设置了numItems之后layout的尺寸还未更新
  1825. if (!t._virtual && t._layout && t._layout.enabled)
  1826. t._layout.updateLayout();
  1827. let pos = t.getItemPos(listId);
  1828. if (!pos) {
  1829. return DEV && console.error('pos is null', listId);
  1830. }
  1831. let targetX: number, targetY: number;
  1832. switch (t._alignCalcType) {
  1833. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  1834. targetX = pos.left;
  1835. if (offset != null)
  1836. targetX -= t._thisNodeUt.width * offset;
  1837. else
  1838. targetX -= t._leftGap;
  1839. pos = new Vec3(targetX, 0, 0);
  1840. break;
  1841. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  1842. targetX = pos.right - t._thisNodeUt.width;
  1843. if (offset != null)
  1844. targetX += t._thisNodeUt.width * offset;
  1845. else
  1846. targetX += t._rightGap;
  1847. pos = new Vec3(targetX + t._contentUt.width, 0, 0);
  1848. break;
  1849. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  1850. targetY = pos.top;
  1851. if (offset != null)
  1852. targetY += t._thisNodeUt.height * offset;
  1853. else
  1854. targetY += t._topGap;
  1855. pos = new Vec3(0, -targetY, 0);
  1856. break;
  1857. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  1858. targetY = pos.bottom + t._thisNodeUt.height;
  1859. if (offset != null)
  1860. targetY -= t._thisNodeUt.height * offset;
  1861. else
  1862. targetY -= t._bottomGap;
  1863. pos = new Vec3(0, -targetY + t._contentUt.height, 0);
  1864. break;
  1865. }
  1866. let viewPos: any = t.content.getPosition();
  1867. viewPos = Math.abs(t._sizeType ? viewPos.y : viewPos.x);
  1868. let comparePos = t._sizeType ? pos.y : pos.x;
  1869. let runScroll = Math.abs((t._scrollPos != null ? t._scrollPos : viewPos) - comparePos) > .5;
  1870. // cc.log(runScroll, t._scrollPos, viewPos, comparePos)
  1871. // t._scrollView.stopAutoScroll();
  1872. if (runScroll) {
  1873. t._scrollView.scrollToOffset(pos, timeInSecond);
  1874. t._scrollToListId = listId;
  1875. t._scrollToEndTime = ((new Date()).getTime() / 1000) + timeInSecond;
  1876. // cc.log(listId, t.content.width, t.content.getPosition(), pos);
  1877. t._scrollToSo = t.scheduleOnce(() => {
  1878. if (!t._adheringBarrier) {
  1879. t.adhering = t._adheringBarrier = false;
  1880. }
  1881. t._scrollPos =
  1882. t._scrollToListId =
  1883. t._scrollToEndTime =
  1884. t._scrollToSo =
  1885. null;
  1886. //cc.log('2222222222', t._adheringBarrier)
  1887. if (overStress) {
  1888. // t.scrollToListId = listId;
  1889. let item = t.getItemByListId(listId);
  1890. if (item) {
  1891. tween(item)
  1892. .to(.1, { scale: 1.05 })
  1893. .to(.1, { scale: 1 })
  1894. .start();
  1895. }
  1896. }
  1897. }, timeInSecond + .1);
  1898. if (timeInSecond <= 0) {
  1899. t._onScrolling();
  1900. }
  1901. }
  1902. }
  1903. /**
  1904. * 计算当前滚动窗最近的Item
  1905. */
  1906. _calcNearestItem() {
  1907. let t: any = this;
  1908. t.nearestListId = null;
  1909. let data: any, center: number;
  1910. if (t._virtual)
  1911. t._calcViewPos();
  1912. let vTop: number, vRight: number, vBottom: number, vLeft: number;
  1913. vTop = t.viewTop;
  1914. vRight = t.viewRight;
  1915. vBottom = t.viewBottom;
  1916. vLeft = t.viewLeft;
  1917. let breakFor: boolean = false;
  1918. for (let n = 0; n < t.content.children.length && !breakFor; n += t._colLineNum) {
  1919. data = t._virtual ? t.displayData[n] : t._calcExistItemPos(n);
  1920. if (data) {
  1921. center = t._sizeType ? ((data.top + data.bottom) / 2) : (center = (data.left + data.right) / 2);
  1922. switch (t._alignCalcType) {
  1923. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  1924. if (data.right >= vLeft) {
  1925. t.nearestListId = data.id;
  1926. if (vLeft > center)
  1927. t.nearestListId += t._colLineNum;
  1928. breakFor = true;
  1929. }
  1930. break;
  1931. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  1932. if (data.left <= vRight) {
  1933. t.nearestListId = data.id;
  1934. if (vRight < center)
  1935. t.nearestListId += t._colLineNum;
  1936. breakFor = true;
  1937. }
  1938. break;
  1939. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  1940. if (data.bottom <= vTop) {
  1941. t.nearestListId = data.id;
  1942. if (vTop < center)
  1943. t.nearestListId += t._colLineNum;
  1944. breakFor = true;
  1945. }
  1946. break;
  1947. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  1948. if (data.top >= vBottom) {
  1949. t.nearestListId = data.id;
  1950. if (vBottom > center)
  1951. t.nearestListId += t._colLineNum;
  1952. breakFor = true;
  1953. }
  1954. break;
  1955. }
  1956. }
  1957. }
  1958. //判断最后一个Item。。。(哎,这些判断真心恶心,判断了前面的还要判断最后一个。。。一开始呢,就只有一个布局(单列布局),那时候代码才三百行,后来就想着完善啊,艹..这坑真深,现在这行数都一千五了= =||)
  1959. data = t._virtual ? t.displayData[t.displayItemNum - 1] : t._calcExistItemPos(t._numItems - 1);
  1960. if (data && data.id == t._numItems - 1) {
  1961. center = t._sizeType ? ((data.top + data.bottom) / 2) : (center = (data.left + data.right) / 2);
  1962. switch (t._alignCalcType) {
  1963. case 1://单行HORIZONTAL(LEFT_TO_RIGHT)、网格VERTICAL(LEFT_TO_RIGHT)
  1964. if (vRight > center)
  1965. t.nearestListId = data.id;
  1966. break;
  1967. case 2://单行HORIZONTAL(RIGHT_TO_LEFT)、网格VERTICAL(RIGHT_TO_LEFT)
  1968. if (vLeft < center)
  1969. t.nearestListId = data.id;
  1970. break;
  1971. case 3://单列VERTICAL(TOP_TO_BOTTOM)、网格HORIZONTAL(TOP_TO_BOTTOM)
  1972. if (vBottom < center)
  1973. t.nearestListId = data.id;
  1974. break;
  1975. case 4://单列VERTICAL(BOTTOM_TO_TOP)、网格HORIZONTAL(BOTTOM_TO_TOP)
  1976. if (vTop > center)
  1977. t.nearestListId = data.id;
  1978. break;
  1979. }
  1980. }
  1981. // cc.log('t.nearestListId =', t.nearestListId);
  1982. }
  1983. //上一页
  1984. prePage(timeInSecond: number = .5) {
  1985. console.log('👈');
  1986. if (!this.checkInited())
  1987. return;
  1988. console.log('LEFT', this.curPageNum);
  1989. this.skipPage(this.curPageNum - 1, timeInSecond);
  1990. }
  1991. //下一页
  1992. nextPage(timeInSecond: number = .5) {
  1993. console.log('👉');
  1994. if (!this.checkInited())
  1995. return;
  1996. console.log('RIGHT', this.curPageNum);
  1997. this.skipPage(this.curPageNum + 1, timeInSecond);
  1998. }
  1999. //跳转到第几页
  2000. skipPage(pageNum: number, timeInSecond: number) {
  2001. let t: any = this;
  2002. if (!t.checkInited())
  2003. return;
  2004. if (t._slideMode != SlideType.PAGE)
  2005. return console.error('This function is not allowed to be called, Must SlideMode = PAGE!');
  2006. if (pageNum < 0 || pageNum >= t._numItems)
  2007. return;
  2008. if (t.curPageNum == pageNum)
  2009. return;
  2010. console.log(pageNum);
  2011. t.curPageNum = pageNum;
  2012. if (t.pageChangeEvent) {
  2013. EventHandler.emitEvents([t.pageChangeEvent], pageNum);
  2014. }
  2015. t.scrollTo(pageNum, timeInSecond);
  2016. }
  2017. //计算 CustomSize(这个函数还是保留吧,某些罕见的情况的确还是需要手动计算customSize的)
  2018. calcCustomSize(numItems: number) {
  2019. let t: any = this;
  2020. if (!t.checkInited())
  2021. return;
  2022. if (!t._itemTmp)
  2023. return console.error('Unset template item!');
  2024. if (!t.renderEvent)
  2025. return console.error('Unset Render-Event!');
  2026. t._customSize = {};
  2027. let temp: any = instantiate(t._itemTmp);
  2028. let ut: UITransform = temp.getComponent(UITransform);
  2029. t.content.addChild(temp);
  2030. for (let n: number = 0; n < numItems; n++) {
  2031. EventHandler.emitEvents([t.renderEvent], temp, n);
  2032. if (ut.height != t._itemSize.height || ut.width != t._itemSize.width) {
  2033. t._customSize[n] = t._sizeType ? ut.height : ut.width;
  2034. }
  2035. }
  2036. if (!Object.keys(t._customSize).length)
  2037. t._customSize = null;
  2038. temp.removeFromParent();
  2039. if (temp.destroy)
  2040. temp.destroy();
  2041. return t._customSize;
  2042. }
  2043. }