Hello, Everyone.
To complete my aims in learning how to set up Objective-C UIButtons, UIPickerView and UIDatePicker for a Codea project I’m working on, I finally figured out how to set up a UIDate Picker. If others are interested, here is a template example:
-- UIDatePicker
function setup()
viewer.mode = FULLSCREEN
--note: the next statement gets the actual UIViewController running in Codea
local vc = objc.viewer
-- datetime object is in seconds from 1/1/1970 ("epoch start time") to 09/30/2021 = 1633071572
local minDate = objc.NSDate:alloc():initWithTimeIntervalSince1970_(1633071572)
local maxDate = objc.NSDate() -- = today's date (e.g. 12/20/2023)
local DatePicker = objc.UIDatePicker()
DatePicker.preferredDatePickerStyle = objc.enum.UIDatePickerStyle.wheels
DatePicker.backgroundColor = color(255,255,255)
DatePicker.datePickerMode = objc.enum.UIDatePickerMode.date
-- the next two lines are optional
DatePicker.minimumDate = minDate
DatePicker.maximumDate = maxDate
-- next four lines set up format to convert date object pick to a string in short format (e.g. 11/11/2021)
local dateFormatter = objc.NSDateFormatter:alloc():init()
dateFormatter.dateStyle = objc.enum.NSDateFormatterStyle.NSDateFormatterShortStyle
-- NoStyle means don't display the datetime object's time if it has time associated with it
dateFormatter.timeStyle = objc.enum.NSDateFormatterStyle.NSDateFormatterNoStyle
dateString = dateFormatter:stringFromDate_(DatePicker.date)
local actionButton = objc.UIAction:actionWithHandler_(function(objAction) dateString = dateFormatter:stringFromDate_(DatePicker.date) end)
DatePicker:addAction_forControlEvents_(actionButton, objc.enum.UIControlEvents.valueChanged)
vc.view:addSubview_(DatePicker)
DatePicker.translatesAutoresizingMaskIntoConstraints = false
DatePicker.centerXAnchor:constraintEqualToAnchor_(vc.view.centerXAnchor).active = true
DatePicker.topAnchor:constraintEqualToAnchor_constant_(vc.view.topAnchor, HEIGHT/2 - 300).active = true
end
function draw()
background(40, 40, 50)
text(dateString, WIDTH/2, HEIGHT/2 + 20)
end
If others are interested in customizing further the appearance of their UIDatePicker, please see additional customization code from my example in this previous post: