List.ts 87 KB

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