如何检查我的pickerDate是否在Swift中旋转或停止?

时间:2014-09-01 07:40:57

标签: ios swift uidatepicker

我有一个pickerDate,如果我在旋转时尝试保存日期,我的应用程序崩溃了。但是,如果我等待停止旋转选择器,这将正确保存。

我需要检查我的pickerDate是停止还是旋转保存或等待没有崩溃。或者停止这个..我该怎么做?

 datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)


  @IBOutlet weak var datePicker: UIDatePicker!
var date = ""
var age: NSDate!

func handleDatePicker(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy"
    age=sender.date
    date = dateFormatter.stringFromDate(sender.date)
}

func calculateAge (birthday: NSDate) -> NSInteger {

    var calendar : NSCalendar = NSCalendar.currentCalendar()
    var now: NSDate = NSDate()
    var dateComponentNow : NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil)

    return dateComponentNow.year
}
 @IBAction func okButton(sender: UIBarButtonItem) {
    //code to calculate age and save this 
    var ageCalc = calculateAge(age) //Here crash

谢谢!

1 个答案:

答案 0 :(得分:0)

您必须检查(birthday: NSDate)是否可用。因此,只需检查零。

func calculateAge (birthday: NSDate) -> NSInteger {

    if (birthday != nil) {
        var calendar : NSCalendar = NSCalendar.currentCalendar()
        var now: NSDate = NSDate()
        var dateComponentNow : NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear, fromDate: birthday, toDate: now, options: nil)
        return dateComponentNow.year
    }

    return -1;
}

只需检查nil日期,如果是,请返回-1NSIntegerMax以确定您尚未计算出正确的年龄。

更新: if (birthday != nil)或使用if let语法检查nil

func calculateAge (birthday: NSDate!) -> NSInteger {

    if  let thisBirthday = birthday {
        var calendar : NSCalendar = NSCalendar.currentCalendar()
        var now: NSDate = NSDate()
        var dateComponentNow : NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear, fromDate: thisBirthday, toDate: now, options: nil)
        return dateComponentNow.year
    }

    return -1;
}