有倒计时功能的标签这个还是挺常见的
直接上代码吧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
local TimerLabel = class("TimerLabel",function(params) return display.newTTFLabel(params) end) local TimerLabel = class("TimerLabel", function(params) return display.newTTFLabel(params) end) TimerLabel.ON_COUNT_DOWN = "ON_COUNT_DOWN" function TimerLabel:ctor(params) cc(self):addComponent("components.behavior.EventProtocol"):exportMethods() self:setNodeEventEnabled(true) self._triggerTime = params.triggerTime or 0 self._time = params.time self._format = params.format self:setString(self:formatTime(self._time,self._format)) end function TimerLabel:formatTime(timeValue, format) if not timeValue then return "unknow time" end local as = math.floor(timeValue / 1000) local s = as % 60 local am = math.floor(as / 60) local m = am % 60 local h = math.floor(am / 60) local ss = nil if s < 10 then ss = string.format("0%d", s) else ss = string.format("%d", s) end local ms = nil if m < 10 then ms = string.format("0%d", m) else ms = string.format("%d", m) end local hs = nil if h < 10 then hs = string.format("0%d", h) else hs = string.format("%d", h) end local newTimeString = string.gsub(format, "@H", hs) newTimeString = string.gsub(newTimeString, "@M", ms) newTimeString = string.gsub(newTimeString, "@S", ss) return newTimeString end function TimerLabel:update(dt) local lastTime = math.ceil(self._time / 1000) self._time = self._time - dt * 1000 if self._time <= 0 then self._time = 0 end local nowTime = math.ceil(self._time / 1000) if lastTime ~= nowTime then self:setString(self:formatTime(self._time,self._format)) end if self._time <= self._triggerTime then self:dispatchEvent({name = TimerLabel.ON_COUNT_DOWN}) if self._updateEntry then cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self._updateEntry) self._updateEntry = nil end end end function TimerLabel:onEnter() self._updateEntry = cc.Director:getInstance():getScheduler():scheduleScriptFunc(handler(self,self.update),0,false) end function TimerLabel:onExit() if self._updateEntry then cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self._updateEntry) self._updateEntry = nil end end return TimerLabel |
用法如下
1 2 3 4 5 6 7 8 9 10 |
local timerLabel = TimerLabel.new({ time = 60000, format = "TimerLabel演示:@M:@S" }) timerLabel:addEventListener(TimerLabel.ON_COUNT_DOWN,function(event) print("倒计时结束") end) timerLabel:align(display.LEFT_TOP,50,display.height - 50):addTo(self) |
除了text外,display.newTTFLabel里的所有参数都有效
新增了time参数(单位毫秒),format参数(支持H M S),triggerTime参数(触发事件,不传时为0)
倒计时结束会触发TimerLabel.ON_COUNT_DOWN