Nanfeng

Notes on software development, code, and curious ideas

ListView, ScrollView, TableView, and PageView in Cocos2d-x Lua

Cocos2d-x offers several containers with overlapping names but different behavior. Choose one based on layout, data size, and interaction rather than using them interchangeably.

ccui.ListView

ListView lays out item widgets vertically or horizontally and provides selection events:

1
2
3
4
5
6
7
8
9
10
local list = ccui.ListView:create()
list:setContentSize(cc.size(400, 500))
list:setDirection(ccui.ScrollViewDir.vertical)
list:setItemsMargin(8)

for index = 1, 20 do
local button = ccui.Button:create("row.png")
button:setTitleText("Item " .. index)
list:pushBackCustomItem(button)
end

It is convenient for modest lists but creates every item unless the application implements reuse.

ccui.ScrollView

ScrollView is a general scrollable canvas. Set a viewport size and a larger inner-container size, then position children yourself. It is suitable for a mixed layout that does not naturally form identical rows.

cc.TableView

TableView is optimized for large, uniform data sets by reusing visible cells. Its delegate supplies cell count, cell size, and a cell for each index. Reinitialize all visual state when reusing a dequeued cell; otherwise old labels or selection state may leak into a new row.

ccui.PageView

PageView presents one page at a time with swipe navigation:

1
2
3
4
5
6
7
local pages = ccui.PageView:create()
pages:setContentSize(cc.size(600, 360))
for index = 1, 5 do
local layout = ccui.Layout:create()
layout:setContentSize(pages:getContentSize())
pages:addPage(layout)
end

Listen for page-turn events to update an indicator or lazy-load content. Avoid placing competing horizontal scroll gestures inside a page unless gesture ownership is explicit.

Use ListView for convenient small lists, TableView for reusable large lists, ScrollView for free-form content, and PageView for discrete swipeable screens.

+