Как сохранить выборочный контроль выбора
Я добавил в свой проект сегментированный элемент управления, чтобы установить частоту уведомлений (например, ежедневно, еженедельно и т. д.). Я не понимаю, как сохранить выбор пользователя и как установить уведомление об этом выборе. У меня есть AddController, куда пользователь может вставлять напоминания, и в этом контроллере я также хочу установить частоту повторения уведомлений. Код является:
@IBAction func salva(sender: UIButton) {
if fieldNomeMedicina.text.isEmpty &&
fieldData.text.isEmpty &&
fieldDosaggio.text.isEmpty{
//alertView che avverte l'utente che tutti i campi sono obbligatori
//return
}
var therapy = PillsModel(nomeMedicinaIn: fieldNomeMedicina.text,
dosaggioIn : fieldDosaggio.text,
dataIn: fieldData.text
)
profilo.therapyArra.append(therapy)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.pillsTable.reloadData()
dismissViewControllerAnimated(true, completion: nil)
let stringDate = fieldData.text//get the time string
//format date
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm" //format style. Browse online to get a format that fits your needs.
var date = dateFormatter.dateFromString(stringDate)
//date is your NSdate.
var localNotification = UILocalNotification()
localNotification.category = "FIRST_CATEGORY"
localNotification.fireDate = date
localNotification.alertBody = "Take your medicine:" + " " + fieldNomeMedicina.text + " " + fieldDosaggio.text
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
@IBAction func frequencyControl(sender: UISegmentedControl) {
if(segmentedControl.selectedSegmentIndex == 0)
{
notification.repeatInterval = 0;
}
else if(segmentedControl.selectedSegmentIndex == 1)
{
notification.repeatInterval = .CalendarUnitDay;
}
else if(segmentedControl.selectedSegmentIndex == 2)
{
notification.repeatInterval = .CalendarUnitWeekday;
}
else if(segmentedControl.selectedSegmentIndex == 3)
{
notification.repeatInterval = .CalendarUnitMonth;
}
else if(segmentedControl.selectedSegmentIndex == 4)
{
notification.repeatInterval = .CalendarUnitMinute;
}
}
func drawAShape(notification:NSNotification){
var view:UIView = UIView(frame:CGRectMake(10, 10, 100, 100))
view.backgroundColor = UIColor.redColor()
self.view.addSubview(view)
}
func showAMessage(notification:NSNotification){
var message:UIAlertController = UIAlertController(title: "A Notification Message", message: "Hello there", preferredStyle: UIAlertControllerStyle.Alert)
message.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(message, animated: true, completion: nil)
}
У меня есть ошибка: использование неразрешенного идентификатора 'Notification' в Func FrequencyControl.
1 ответ
Ваша проблема в том, что вы создаете только localNotification
после того, как пользователь нажимает кнопку (это хороший выбор дизайна). Это означает, что вы не можете хранить информацию в нем раньше, но в этом нет необходимости - вы всегда можете спросить UISegmentedControl
какова его текущая стоимость.
Вам в основном нужно передать этот блок кода:
if(segmentedControl.selectedSegmentIndex == 0)
{
notification.repeatInterval = 0;
}
...
внутри salva
функция. И пока вы на это, преобразуйте if
заявления к switch
- это намного чище. Это будет выглядеть так:
var localNotification = UILocalNotification()
switch segmentedControl.selectedSegmentIndex {
case 0:
localNotification.repeatInterval = 0;
case 1:
localNotification.repeatInterval = .CalendarUnitDay;
...
}