Google日历应用具有一项功能,您可以自定义何时在事件发生之前发送通知。如果您不熟悉它,它看起来像这样:
Google Calendar Custom Notification
本质上是一个选择器视图,包含两个部分,第一个显示供用户选择的数字,第二个显示时间单位(“分钟”,“小时”,“天”,“周”)。当用户选择时间单位时,数字会更改。例如,如果用户选择“分钟”作为单位,则第一个部分将显示1到60。如果他们选择“小时”,则第一个部分将显示1到24。选择“天”将显示1到28,并且“周”将显示1到4。
我想开发类似的功能,但是当我运行代码时,出现错误“索引超出范围”。该代码块的最后一个函数中发生错误。在调试部分,“行”的值为0。我认为该错误与数组大小的差异有关,但我不确定。感谢所有帮助!
import UIKit
class AlarmSet
{
func timeIntervals() -> [String]
{
return ["minutes", "hours", "days", "weeks"]
}
func timeValues(time: String) -> [Int]
{
switch time
{
case "minutes":
return Array(1...60)
case "hours":
return Array(1...24)
case "days":
return Array(1...28)
case "weeks":
return [1, 2, 3, 4]
default:
return [0]
}
}
}
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate
{
@IBOutlet weak var addAlarm: UIButton!
@IBOutlet weak var alarmView: UIPickerView!
//The first component of the picker displays numbers
var picker1Options:[Int] = []
//The second picker displays units of time (minutes, hours, etc.)
var picker2Options:[String] = []
override func viewDidLoad()
{
super.viewDidLoad()
alarmView.delegate = self
alarmView.dataSource = self
alarmView.delegate?.pickerView?(alarmView, didSelectRow: 0, inComponent: 0)
alarmView.delegate?.pickerView?(alarmView, didSelectRow: 0, inComponent: 1)
alarmView.isHidden = true
let alarm = AlarmSet();
picker2Options = alarm.timeIntervals()
let firstValue = picker2Options[0]
picker1Options = alarm.timeValues(time: firstValue)
// Do any additional setup after loading the view.
}
func numberOfComponents(in pickerView: UIPickerView) -> Int
{
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
if component == 1
{
return picker2Options.count
}
else
{
return picker1Options.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
if component == 0
{
return "\(picker1Options[row])"
}
else
{
return "\(picker2Options[row])"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if component == 1
{
let alarm = AlarmSet();
//Out of range error is on this next line
let currentValue = picker2Options[row]
picker1Options = alarm.timeValues(time: currentValue)
pickerView.reloadAllComponents()
}
}
}
您正在打电话
alarmView.delegate?.pickerView?(alarmView, didSelectRow: 0, inComponent: 0
在设置picker2Options变量之前,在viewDidLoad中,因此当picker2Options为空时,它试图访问picker2Options [0]。在调用委托方法之前设置数组