I would like to set a default date value in inputView.
I have:
func createDatePickerDgeb1() {
datePickergeb.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressedgeb1))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.setItems([spaceButton,doneButton], animated: false)
gebdatum.inputAccessoryView = toolbar
gebdatum.inputView = datePickergeb
}
The picker view shows me current date. Is possible that I can show for example the "01.01.1960" as a default?
// Create date components
var dateComponents = DateComponents()
dateComponents.year = 1960
dateComponents.month = 1
dateComponents.day = 1
// Create date from components
let userCalendar = Calendar.current // user calendar
let date = userCalendar.date(from: dateComponents)
// Set datePicker date
datePickergeb.setDate(date, animated: false)
Related
I’m using time pickers and they work correctly as expected but the problem that i dont want to user to reserve a past time. when i click on the time pickers they doesn’t allow me to reserve past time but the problem is when i leave it opened and time continues it allow me to choose past time which is the time i click on it for example i opened time picker at 10:11 when i leave time picker opened and its 10:12 it allow me to choose 10:11 which is in past. when 10:11 is done it shouldn’t be clickable. Hope its clear and this is my code if you can help
func createTimePicker() {
StartTimeTxt.textAlignment = .center
EndTimeTxt.textAlignment = .center
//tool bar
let toolbar = UIToolbar()
toolbar.sizeToFit()
//bar button(
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
toolbar.setItems([doneBtn], animated: true)
//assign tool bar
StartTimeTxt.inputAccessoryView = toolbar
EndTimeTxt.inputAccessoryView = toolbar
// assign time picker to the txt field
StartTimeTxt.inputView = StartTimePicker
EndTimeTxt.inputView = EndTimePicker
let calendar = Calendar.current
//First range
let startTime = Date()
let startRangeEnd = calendar.date(byAdding: DateComponents(minute: 30), to: startTime)!
let startRange = startTime...startRangeEnd
//Second range
let endTime = calendar.date(byAdding: DateComponents(minute: 1), to: startRangeEnd)!
let endRangeEnd = calendar.startOfDay(for: calendar.date(byAdding: DateComponents(day: 1), to: startTime)!)
let endRange = endTime...endRangeEnd
StartTimePicker.date = startTime
StartTimePicker.minimumDate = startTime
StartTimePicker.maximumDate = startRangeEnd
EndTimePicker.date = endTime
EndTimePicker.minimumDate = endTime
EndTimePicker.maximumDate = endRangeEnd
if #available(iOS 13.4, *) {
StartTimePicker.preferredDatePickerStyle = .wheels
EndTimePicker.preferredDatePickerStyle = .wheels
}
} ```
I'm using time pickers and I want to store the two values to use them in calculating price, store in firebase.
This is my UI to simplify the idea
The problem is that i don't know which part I can use to store the value of start time and end time (the numbers in UI are written in arabic)
This is my code, can you guide me to the way to store the UITextField values?
#IBOutlet weak var StartTimeTxt: UITextField!
#IBOutlet weak var EndTimeTxt: UITextField!
func createTimePicker() {
StartTimeTxt.textAlignment = .center
EndTimeTxt.textAlignment = .center
//tool bar
let toolbar = UIToolbar()
toolbar.sizeToFit()
//bar button(
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
toolbar.setItems([doneBtn], animated: true)
//assign tool bar
StartTimeTxt.inputAccessoryView = toolbar
EndTimeTxt.inputAccessoryView = toolbar
// assign time picker to the txt field
StartTimeTxt.inputView = StartTimePicker
EndTimeTxt.inputView = EndTimePicker
//time picker mode
/* StartTimePicker.datePickerMode = .time
EndTimePicker.datePickerMode = .time*/
let calendar = Calendar.current
//First range
let startTime = Date()
let startRangeEnd = calendar.date(byAdding: DateComponents(minute: 30), to: startTime)!
let startRange = startTime...startRangeEnd
//Second range
let endTime = calendar.date(byAdding: DateComponents(minute: 1), to: startRangeEnd)!
let endRangeEnd = calendar.startOfDay(for: calendar.date(byAdding: DateComponents(day: 1), to: startTime)!)
let endRange = endTime...endRangeEnd
StartTimePicker.date = startTime
StartTimePicker.minimumDate = startTime
StartTimePicker.maximumDate = startRangeEnd
EndTimePicker.date = endTime
EndTimePicker.minimumDate = endTime
EndTimePicker.maximumDate = endRangeEnd
if #available(iOS 13.4, *) {
StartTimePicker.preferredDatePickerStyle = .wheels
EndTimePicker.preferredDatePickerStyle = .wheels
}
}
I have time picker set up. Local notification takes time from the time picker and sends the notification.
I have three notification with identifiers notfica2, notifica3 and notifica 4.
Now, I want to repeat notifica 2 and notifica3 every weekday (Monday to Friday) and repeat notifica 4 every weekend (Saturday-Sunday).
I didn't pick dates for the notificas. So I think timePicker automatically picks the date the time was set.
Please show me how to implement this specific repeat option.
Also, I have another bug. Lets say when I am picking the time it is 5 pm. And I want to set time 3 pm for notifica2 and notifica3 (which I want to repeat every weekday)
The exception says negative time. I understand the issue but I need a fix. So, if I put 3 pm but its already 6 pm then the 3pm notification will be sent the next day if it is not Saturday or Sunday. Same with notifica 4. But instead this will shift by 5 days for next Saturday.
Here is my code so far.
This is a small part of a larger app.
var textfield: UITextField!
let timePicker = UIDatePicker()
let timePicker2 = UIDatePicker()
let timePicker3 = UIDatePicker()
func timePickerFunction(){
//toolbar
timePicker.datePickerMode = UIDatePickerMode.time
timePicker2.datePickerMode = UIDatePickerMode.time
timePicker3.datePickerMode = UIDatePickerMode.time
let toolBar = UIToolbar()
toolBar.sizeToFit()
//DoneButton
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector (donePressed))
toolBar.setItems([doneButton], animated: false)
BWTimePicker.inputAccessoryView = toolBar
AWTimePicker.inputAccessoryView = toolBar
ODTimePicker.inputAccessoryView = toolBar
//Assigning timepicker to the text fields
BWTimePicker.inputView = timePicker
AWTimePicker.inputView = timePicker2
ODTimePicker.inputView = timePicker3
}
func donePressed(){
//Formatting the date.
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
// BWTimePicker.text = "\(timePicker.date)"
// AWTimePicker.text = "\(timePicker.date)"
// ODTimePicker.text = "\(timePicker.date)"
// self.view.endEditing(true)
if BWTimePicker.isEditing {
//do something to textfield1
BWTimePicker.text = dateFormatter.string(from: timePicker.date)
self.view.endEditing(true)
}
else if AWTimePicker.isEditing {
//do something to textfield2
AWTimePicker.text = dateFormatter.string(from: timePicker2.date)
self.view.endEditing(true)
}
else if ODTimePicker.isEditing {
//do something to textfield2
ODTimePicker.text = dateFormatter.string(from: timePicker3.date)
self.view.endEditing(true)
}
// self.view.endEditing(true)
}
#IBAction func updateTime(_ sender: UIButton) {
//1. Get text from three UITextField objects.
let stringBW = BWTimePicker.text
let stringAW = AWTimePicker.text
let stringOD = ODTimePicker.text
//2. If the three time fields are not empty , we would send the notificaiton
if !(stringBW?.isEmpty)! && !(stringAW?.isEmpty)! && !(stringOD?.isEmpty)! {
//3. We would create a dictionary object which would be send in the notification
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hi!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Your Satisfier Quote is Ready", arguments: nil)
content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
var timeInterval1: Double = 0
var timeInterval2: Double = 0
var timeInterval3: Double = 0
let date = timePicker.date
let date2 = timePicker2.date
let date3 = timePicker3.date
timeInterval1 = date.timeIntervalSinceNow
timeInterval2 = date2.timeIntervalSinceNow
timeInterval3 = date3.timeIntervalSinceNow
print("HMMMMMMMMMKMKMKMKSMKDMSKDMSK")
print(timeInterval1)
print(timeInterval2)
print(timeInterval3)
setNotification(timeInterval:timeInterval1,identifier: "notific2", date: date)
setNotification(timeInterval:timeInterval2,identifier: "notific3", date: date2)
setNotification(timeInterval:timeInterval3,identifier: "notific4", date: date3)
self.isProfileViewVisible = true
self.extraViewTopConstraint2.constant = 1000
self.profileViewTopConstraint.constant = 150
}
else{
//2. Ask user to enter text in all the fields.
self.isProfileViewVisible = true
self.extraViewTopConstraint2.constant = 1000
self.profileViewTopConstraint.constant = 150
}
}
func setNotification (timeInterval : Double, identifier : String, date : Date){
let A: Int = 0
let B: Int = codeTwo.count
let C: Int = codeOne.count
let D: Int = codeThree.count
let number1 = Int (arc4random_uniform(UInt32(B - 1)))
let number2 = Int (arc4random_uniform(UInt32(C - 1)))
let number3 = Int (arc4random_uniform(UInt32(D - 1)))
//Repeat fundtion only added to notifica 2 for experimaental purpose/
if(identifier == "notific2"){
let content: UILocalNotification = UILocalNotification()
content.category = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.alertBody = NSString.localizedUserNotificationString(forKey: "\(codeTwo[number1])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.soundName = UILocalNotificationDefaultSoundName
let time = date
content.fireDate = time
content.repeatInterval = NSCalendar.Unit.day
// let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: time as Date)
//
// let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
// repeats: true)
//
// //let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
// let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
//
// let center = UNUserNotificationCenter.current()
// center.add(request)
UIApplication.shared.scheduleLocalNotification(content)
}
if(identifier == "notific3"){
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "\(codeThree[number3])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
}
if(identifier == "notific4"){
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "\(codeOne[number2])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
}
}
//MARK: ViewController lifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.customization()
self.collectionView.allowsMultipleSelection = true
searchBar.delegate = self
//searchBar.returnKeyType = UIReturnKeyType.done
items = items1
self.navigationController?.isNavigationBarHidden = true
timePickerFunction()
// (sender as AnyObject).setTitle("Add to Group", for: [])
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound])
{
(granted, error) in
self.notificationGranted = granted
if let error = error {
print("granted, but Error in notification permission:\(error.localizedDescription)")
}
}
}
I'm trying to set a minimum and maximum date to limit the selection of the user, but it doesn't work:
override func viewDidLoad() {
let datePickerView : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
tfDateNaissance.inputView = datePickerView
let gregorian: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let currentDate: NSDate = NSDate()
let components: NSDateComponents = NSDateComponents()
components.year = -18
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
components.year = -150
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate
datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
let pickerToolBar = UIToolbar()
pickerToolBar.barStyle = UIBarStyle.Black //you can change the style
pickerToolBar.translucent = true
pickerToolBar.tintColor = UIColor.whiteColor() // or other colours
pickerToolBar.sizeToFit()
let spaceButtonPicker = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let cancelButtonPicker = UIBarButtonItem(title: "Ok", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelDatePicker:")
pickerToolBar.setItems([cancelButtonPicker, spaceButtonPicker], animated: false)
pickerToolBar.userInteractionEnabled = true
tfDateNaissance.inputAccessoryView = pickerToolBar
}
func datePickerValueChanged(sender: UIDatePicker) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
//
// dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
tfDateNaissance.text = dateFormatter.stringFromDate(sender.date)
}
func cancelDatePicker(sender: UIBarButtonItem){
if tfProjet.isFirstResponder(){
tfProjet.resignFirstResponder()
} else if tfDateNaissance.isFirstResponder(){
tfDateNaissance.resignFirstResponder()
}
}
I found this code on stack overflow, I get no errors, but I can select 2200 as year for exemple. I think it's because it's an input view, so how to to ?
The minDate was later than the maxDate:
components.year = -150
let minDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
components.year = -18
let maxDate: NSDate = gregorian.dateByAddingComponents(components, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
datePickerView.minimumDate = minDate
datePickerView.maximumDate = maxDate
I have a UIDatePicker that is set to the hour the minutes then AM/PM. How do I make it so that it is set to the 24 hour system like in the UK? For example 1 would be 13 and there wouldn't be AM or PM.
var datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.Time
datePicker.locale = NSLocale(localeIdentifier: "en_GB") // using Great Britain for this example
Using Swift 4
I have used the following the method to help me achieve a time-picker without AM / PM.
Note i am using TextField as Inputview
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
showTimePicker()
return true
}
func showTimePicker() {
timePicker.datePickerMode = .time
timePicker.locale = Locale(identifier: "en_GB") // Change to your locale
let toolbar = UIToolbar();
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneTimePicker));
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelTimePicker));
toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
modifiedHoursTextField.inputAccessoryView = toolbar
modifiedHoursTextField.inputView = timePicker
}
#objc func doneTimePicker() {
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
modifiedHoursTextField.text = timeFormatter.string(from: timePicker.date)
self.view.endEditing(true)
}
#objc func cancelTimePicker() {
self.view.endEditing(true)
}
Bonus to JAL's answer, if you also want to be able to pick "date", you can use something like below:
viewDidLoad:
deadlineTF.inputView = deadlineDatePicker
deadlineDatePicker.timeZone = NSTimeZone.local
deadlineDatePicker.datePickerMode = UIDatePickerMode.dateAndTime
deadlineDatePicker.locale = Locale(identifier: "tr_TR")
deadlineDatePicker.backgroundColor = UIColor.white
deadlineDatePicker.layer.cornerRadius = 5.0
deadlineDatePicker.layer.shadowOpacity = 0.5
deadlineDatePicker.addTarget(self, action: #selector(onDidChangeDate), for: .valueChanged)
.
The Function:
// called when the date picker called.
#objc func onDidChangeDate(sender: UIDatePicker){
// date format
let myDateFormatter: DateFormatter = DateFormatter()
myDateFormatter.dateFormat = "dd/MM/yyyy HH:mm"
// get the date string applied date format
let mySelectedDate = myDateFormatter.string(from: sender.date)
deadlineTF.text = mySelectedDate
}