我正在尝试使用日期选择器的小时和分钟,并添加一个通知。当用户立即从DatePicker中选择小时和分钟时,它现在正在工作。我的问题是,我只想在用户单击“按钮保存”时创建通知,而不是在更改选择器的值时创建通知。我该怎么办?
@objc func printMedHour(sender: UIDatePicker) {
let date = DateFormatter()
date.timeStyle = .short
let dateString = date.string(from: datePicker.date)
let dateAsString = (dateString)//"1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let dates = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: dates!)
//print(dateString)
print(Date24)
let hour = Date24.prefix(2)
let minutes = Date24.suffix(2)
print(hour)
print(minutes)
let content = UNMutableNotificationContent()
content.title = "Time to take your med"
content.body = "Don't forget"
var dateComponent = DateComponents()
dateComponent.calendar = Calendar.current
let hourString = (hour)
let hourInt = Int(hourString)
print(hourInt)
let minuteString = (minutes)
let minuteInt = Int(minuteString)
print(minuteInt)
//dateComponent.weekday = 7 //Saturday
dateComponent.hour = (hourInt) as? Int //Hour
dateComponent.minute = (minuteInt) as! Int //Minute
//Trigger:
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request, withCompletionHandler: {(error) in
if error != nil {
print("Error")
}
})
self.reminderTextField.text = dateString
view.endEditing(true)
}
我的按钮如下:
let saveButton: UIButton = {
let button = UIButton()
button.setTitle("Save", for: .normal)
button.backgroundColor = UIColor.rgb(red: 40, green: 40, blue: 40)
button.contentMode = .center
button.titleLabel?.textColor = .white
button.titleLabel?.font = UIFont(name: "Verdana", size: 20)
button.addTarget(self, action: #selector(saveUserSettings), for: .touchUpInside)
button.isOpaque = true
button.layer.opacity = 0.9
button.addTarget(self, action: #selector(AddMedViewController.printMedHour(sender:)), for: UIControl.Event.valueChanged)
return button
}()
将目标添加到日期选择器时,不会创建通知。 我在做什么错了?
谢谢!