Strange date picker behaviour Xcode, swift 3

隐身守侯 提交于 2020-01-07 03:52:19

问题


My current project is a timer which uses a date picker to set the amount of time the user wants before the timer goes off (say 1 minute, 6 hours and two minutes etc.). The problem lies in the amount of time that the date picker believes it has been set for. Below is the code which I am using to set the time.

@IBOutlet weak var datePicker: UIDatePicker!

var timeAmount:Double = 0

@IBAction func startButton() {
    timeAmount = Double(datePicker.countDownDuration)
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeAmount, repeats: false)
}

Here it can be seen that the function startButton, sets the value of timeAmount to be the amount of time that the date picker is set for. This timeAmount value is then used in a local notification as the time.

The issue is that the datePicker.countDownDuration is never correct. If it is set for one minute, then timeAmount may return a value of 99 seconds, 62 seconds, 67 seconds etc. It is just completely random.

Maybe I do not entirely understand how the .countDownDuration feature works, however from everything I have read, this should return a value of 60 seconds.

Any thoughts and suggestions on the matter will be very much appreciated, thank you.


回答1:


By default, the UIDatePicker will take the current second value for the calculation.

timeAmount = (number of minutes selected in picker * 60) + current time second value.

For example:
If the current time is 13:40:25 (1 PM 40 minutes 25 seconds) and you have selected one minute in the date picker, the value of timeAmount in this case is 85.

timeAmount = (1*60) + 25

This will solve your problem.

  1. Go to your Storyboard and select UIDatapicker. Navigate to Date option in Attributes inspector.

  2. Click the Dropdown and change it to Custom from Current Date.

  3. You will see a new text field with the current time as the custom date.

  4. Just change the second field to 00.

  5. Run the App now. Now it will take 0 as the value for the second and you will able to see seconds value correctly based on the time you are choosing in the date picker.

Hope this will solve your problem.



来源:https://stackoverflow.com/questions/43384427/strange-date-picker-behaviour-xcode-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!