UIPickerViewで選択された行の値を取得しようとしています。選択した行に応じて、繰り返す通知の時間間隔を設定します。すなわち、ユーザはUIPickerViewで「毎2分」を選択し、120.0秒ごとに通知を受ける。UIPickerViewの選択した値を通知の時間間隔として使用する方法は?
2番目の「didSelectRow」メソッドは、変数interval
に値を格納していないようですが、これまでの解決策は見つかりませんでした。
これは、これまでの私のコードです:
import UIKit
import UserNotifications
import UserNotificationsUI
class ViewController: UIViewcontroller, UIPickerViewDataSource, UIPickerViewDelegate {
// The following lines define the parameters for Picker View
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myPicker: UIPickerView!
let pickerData = ["Every minute", "Every 2 minutes", "Every 3 minutes", "Every 4 minutes", "Every 5 minutes", "Every 6 minutes", "Every 7 minutes", "Every 8 minutes", "Every 9 minutes", "Every 10 minutes"]
override func viewDidLoad() {
super.viewDidLoad()
myPicker.delegate = self
myPicker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
myLabel.text = pickerData[row]
}
var interval: TimeInterval = 60.0 // Assume that row 0 is selected by default
// The following method might be the tricky part I guess.
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) {
interval = Double(row+1) * 60.0
}
let requestIdentifier = "SampleRequest" //identifier is to cancel the notification request
@IBAction func triggerNotification(){
print("notification will be triggered in five seconds..Hold on tight")
let content = UNMutableNotificationContent()
content.title = "Placeholder"
content.subtitle = "Placeholder"
content.body = "Placeholder"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval:self.interval, repeats: true)
let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().add(request){(error) in
if (error != nil){
print(error?.localizedDescription ?? "User instance is nil")
}
}
}
@IBAction func stopNotification(_ sender: AnyObject) {
print("Removed all pending notifications")
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [requestIdentifier])
}
}
誰もこれで私を助けることができますか?
時間に対応する値の配列を作成し、次にピッカービューの選択したインデックスを使用して配列から値を取得する必要があります – Paulw11
私はこれについてあなたに従うことができるか分かりません。値の配列は、60.0,120.0などの配列を意味しますか?そして、他の配列から値を取得するために、pickerviewの選択されたインデックスをどのように使用しますか? – Adrian
正確です。それでは単純に 'timeDelay = times [row]' – Paulw11