一个日期选择滚轮组件,可以根据每个月不同的天数进行调整,甚至可以考虑闰年!
问题
来自小部件库的传统 PickerWidget(widget.newPickerWheel())是有限的,因为一旦创建它,就无法真正修改列的内容。这对于选择日期来说会产生一个问题,因为每个月的天数都不同。PickerWidget 的示例代码会引导你如何将其用于日期选择,但是如果你按照该示例,最终用户可能会选择一个不存在的日期,例如 2 月 31 日。
解决方案
现在,我确信有人可以改进我在这里开始的内容,但是到目前为止,这对我很有效!通过使用计时器,该组件会检查选定的月份(以及年份,以考虑闰年)何时发生了更改。如果中间日期列中的天数需要更新,则它在底层使用的 PickerWidget 将被替换为一个新的 PickerWidget,并保持你的日期选择。
添加到你的应用
首先,将 datePickerWheel.lua 文件下载到你的项目目录。然后,在你的场景中包含必要的模块
local widget = require("widget")
require("datePickerWheel")
-- Create a forward reference for the widget.
local datePicker
接下来,创建小部件。如果你正在使用 composer,则这可能放在你的 scene:create 函数中
-- Create the widget. Depending on where you reference the wd
datePicker = widget.newDatePickerWheel(currYear, currMonth, currDay)
-- Position it however you like.
-- The datePicker is a group containing a picker wheel, so you must use anchorChildren to move everything all seamlessly.
datePicker.anchorChildren = true
datePicker.anchorX = 0.5
datePicker.anchorY = 0
datePicker.x = display.contentCenterX
datePicker.y = 0
sceneGroup:insert(datePicker)
准备就绪后,像清理任何其他小部件一样清理它
datePicker:removeSelf()
datePicker = nil
最后,像使用普通的 PickerWidget 一样访问用户的选择
local values = datePicker:getValues()
-- CORONA BUG: Sometimes the values can be nil.
-- This happens when one of the tables stopped scrolling but hasn't "snapped" to a selected index.
-- Prompt the user to fix the bad column.
if not values[1] then
native.showAlert(_M.appName, "Please make sure a month is selected.", {"OK"})
elseif not values[2] then
native.showAlert(_M.appName, "Please make sure a day is selected.", {"OK"})
elseif not values[3] then
native.showAlert(_M.appName, "Please make sure a year is selected.", {"OK"})
else
displayText.text = values[1].value .. " " .. values[2].value .. ", " .. values[3].value
end
请务必试用 example.lua 场景,以获得一个可运行的示例。请告诉我你的想法,以及你是否有任何改进!
适用于 Corona 版本:
2015.2596
贡献者:
mdsandell