繼上一篇的鬧鐘功能及介面介紹之後,今天要來介紹 PickerView 程式碼的功能喔!
因為我們需要新增新的鬧鐘給 Realm 和 程式本身去呼叫 Notifiction 去跳出通知,所以我們第一步要先去撰寫跳到 “新增頁面” 的程式碼
@IBAction func alarm_insert(_ sender: Any) {
let alarm_insertVC = alarm_insertVC()
self.navigationController?.pushViewController(alarm_insertVC, animated: false)
}
這邊需要去編輯鬧鐘的時間,所以我們必須放一個 PickerView 來判斷的時間設置
我們要先建立一個 0 ~ 23 (時) 、 0 ~ 59 (分) 的陣列放進單例,可以拿來傳值,也可以判斷 PickerView 要給出的值
class time {
let hour = [Int](0...23)
let minute = [Int](0...59)
static let time_shared = time()
private init() {}
}
我們還要在下面打出 PickerView 監聽的程式碼
extension alarm_insertVC : UIPickerViewDelegate,UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2 // 回傳行直列數
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return time.time_shared.hour.count
}
else {
return time.time_shared.minute.count
}
} //回傳每一直列的行列數(component 指的是選到哪個直列)
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
if time.time_shared.hour[row] < 10 {
return "0\(time.time_shared.hour[row])"
}
else {
return "\(time.time_shared.hour[row])"
}
}
else {
if time.time_shared.minute[row] < 10 {
return "0\(time.time_shared.minute[row])"
}
else {
return "\(time.time_shared.minute[row])"
}
}
} //顯示每一行列給的值(如果是個位數,前面補 0)
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
hour_select = time.time_shared.hour[row]
}
else if component == 1 {
minute_select = time.time_shared.minute[row]
}
} //將選取的值放到 hour_select 變數和 minute_select變數