如何将12:02:21.3213
之类的字符串值解析为NSTimeInterval
?从iOS8开始提供的NSDateComponentsFormatter
仅支持格式化,而不支持解析。
答案 0 :(得分:9)
Bartosz Hernas提供的解决方案为我工作,谢谢!
为方便起见,这里是 Swift 3 :
func parseDuration(_ timeString:String) -> TimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.components(separatedBy: ":")
for (index, part) in parts.reversed().enumerated() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}
答案 1 :(得分:7)
以下是如何在Swift中执行此操作:
func parseDuration(timeString:String) -> NSTimeInterval {
guard !timeString.isEmpty else {
return 0
}
var interval:Double = 0
let parts = timeString.componentsSeparatedByString(":")
for (index, part) in parts.reverse().enumerate() {
interval += (Double(part) ?? 0) * pow(Double(60), Double(index))
}
return interval
}
它适用于像
2:12:12
,
02:01:23.123213
答案 2 :(得分:5)
这是我用@Bartosz答案制作的Swift 5版本
def ShowAnotherWin(i=0):
if i < len(YourImageList):
win = Toplevel()
image = ImageTk.PhotoImage(file='C:/Users/capture.PNG')
win.geometry(YourImageList[i])
canvas =Canvas(win, width=420, height=560)
canvas.create_image(0, 0, image= image, anchor=NW)
canvas.pack()
canvas.image = image # need to keep a reference to image
win.overrideredirect(1)
#win.mainloop() # no need to call mainloop() here
root.after(4000, ShowAnotherWin, i+1)
...
ShowAnotherWin()