问题描述
我的代码返回错误:致命错误:浮点值无法转换为UInt8,因为它大于UInt8.max。按下按钮时(在不同的swift文件中)调用代码,但我知道问题不在于调用函数,所以我没有包含它。
My code returns the error: fatal error: floating point value can not be converted to UInt8 because it is greater than UInt8.max. The code is being called when a button is pressed (in a different swift file) but I know that the problem wasn't with calling the function so I didn't include it.
代码:
//starts the timer
func startTimer(sender: AnyObject)
{
if !timer.valid
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: sender, selector: Selector(updateTime()), userInfo: nil, repeats: true)
startTime = NSDate.timeIntervalSinceReferenceDate()
//disp = timerDisplay
}
}
//function that configures the timer
func updateTime()
{
var currentTime = NSDate.timeIntervalSinceReferenceDate()
//find the difference between the current time and the start time
var elapsedTime: NSTimeInterval = currentTime - startTime
//calculate the seconds in elapsed time
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
///find out the fraction of milliseconds to be displayed
let fraction = UInt8(elapsedTime * 10)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
//let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes)
let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds)
let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction)
//display the time left to a string
timerDisplay = "\(strSeconds):\(strFraction)"
}
func stopTimer()
{
timer.invalidate()
}
推荐答案
我会采取不同的方法,因为你需要多次代表NSTimeInterval,所以你应该考虑增加一个读取只计算属性作为项目的扩展,返回它的字符串表示形式如下:
I would take a different approach at it since you will need to represent NSTimeInterval many times, so you should consider adding a read-only computed property as an extension to your project to return a string representation of it as follow:
extension NSTimeInterval {
var time:String {
return String(format:"%d:%02d:%02d.%02d", Int(self/3600.0), Int((self/60.0) % 60), Int((self) % 60 ), Int(self*100 % 100 ))
}
}
class ViewController: UIViewController {
//declarations
@IBOutlet weak var tappedLabel: UILabel!
@IBOutlet weak var timerLabel: UILabel!
var startTime = NSTimeInterval()
var timer = NSTimer()
//starts the timer
func startTimer(sender: AnyObject) {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: sender, selector: "updateTime", userInfo: nil, repeats:true)
startTime = NSDate.timeIntervalSinceReferenceDate()
}
}
// calculates the elapsed time in seconds (Double = NSTimeInterval).extension NStimeInterval
func updateTime() {
//find the difference between the current time and the start time and return a string out of it
// updates the text field
timerLabel.text = (NSDate.timeIntervalSinceReferenceDate() - startTime).time
}
这篇关于NSTimer:浮点值无法转换为UInt8,因为它大于UInt8.max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!