今天在模仿一個demo,想自己去完善一些功能,自己寫的時候就遇見了一個坑。。。先看代碼:
local label = cc.ui.UILabel.new({ UILabelType = 1, text = "Max Score 10", font = "fonts/font-issue1343.fnt", x = boardSize.width / 2, y = boardSize.height * 0.4, }):addTo(self.overboard) :setAnchorPoint(0.5, 0.5)
當我調用label:setString()的時候,竟然沒變化,看輸出信息,發現label是nil!!!我就奇怪來了,後來去找源碼樣例,看看是不是我哪寫錯了。代碼如下:
local label = cc.ui.UILabel.new({ text = "", size = 14, color = display.COLOR_BLACK }):align(display.LEFT_CENTER, display.left + 60, display.top - 60) :addTo(self)
這個代碼中的label就不爲nil,都是用cc.ui.UILabel.new創建的爲什麼不一樣呢?原來問題出在後面函數的調用上。看源碼:
function Node:addTo(target, zorder, tag) target:addChild(self, zorder or self:getLocalZOrder(), tag or self:getTag()) return self end
function Node:align(anchorPoint, x, y) self:setAnchorPoint(display.ANCHOR_POINTS[anchorPoint]) if x and y then self:setPosition(x, y) end return self end
addTo和align都會返回調用對象,而setAnchorPoint沒有返回值,在第一段代碼中執行完setAnchorPoint()後沒有對label賦值,所以爲nil;在第二段代碼中調用的函數一直返回調用對象,所以對label賦值了。
addTo是在shortcodes文件裏,align在NodeEx文件裏。shortcodes裏的函數都會返回調用對象本身。
這次踩坑讓我明白,addTo與addChild的區別,也學到shortcodes使用技巧。例如當你創建一個對象不需要在以後改動時,用shortcodes裏封裝的函數,可以省去取名字的過程。(大家也遇見過在同一文件代碼多了,名字難取的情況吧-_-!)
踩坑結束!如有不足之處,請大家指出,一起交流成長!