我试图通过Swift进行倒计时应用,但问题很少,

时间:2015-09-18 04:31:32

标签: ios swift swift2

我正在为Swift的倒计时应用程序编写代码,但有两个问题。

let myComponetns = myCalendar.components(NSCalendarUnit.CalendarUnitYear |
NSCalendarUnit.CalendarUnitHour |
NSCalendarUnit.CalendarUnitMinute |
NSCalendarUnit.CalendarUnitSecond ,
fromDate: myDate)

→在此部分发生错误,它说, NSCalanderUnit没有会员"CalanderUnitYear"

此外,

myInt = myStr.toInt()!

发生错误,它说, Ambiguos引用成员"String.init"

原因是什么,有人可以告诉我解决方案吗?

class ViewController: UIViewController { 

var cnt : Int = 0 
var timer : NSTimer! 
var myInt:Int = 0 

override func viewDidLoad() { 

    let myDate: NSDate = NSDate() 
    let myCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! 
    let myComponetns = myCalendar.components(NSCalendarUnit.CalendarUnitYear   | 
        NSCalendarUnit.CalendarUnitHour   | 
        NSCalendarUnit.CalendarUnitMinute | 
        NSCalendarUnit.CalendarUnitSecond , 
        fromDate: myDate) 

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onUpdate:", userInfo: nil, repeats: true) 
    timer.fire() 

    var myStr: String = "\(myComponetns.hour)" 
    myStr += "\(myComponetns.minute)" 
    myStr += "\(myComponetns.second)" 

    myInt = myStr.toInt()! 

} 

func onUpdate(timer : NSTimer){ 
    cnt += 1 
    let count = myInt - cnt 
    println(count) 
}

} 

1 个答案:

答案 0 :(得分:0)

首先,NSCalendarUnit成员为YearMonth等,而不是CalendarUnitYearCalendarUnitMonth。此外,在Swift 2中,选项集类型的处理方式略有不同。试试这个:

let myComponents = myCalendar.components([.Year, .Hour, .Minute, .Second],
fromDate: myDate)