簡體   English   中英

'Int'與'String'不同-Swift

[英]'Int' is not identical to 'String' - Swift

在此函數中,我嘗試從UIDatePicker獲取數據並從中減去5。 例如,如果在UIDatePicker中說7:15 AM,它將從小時數中減去並為2:15 AM。 修改后的代碼無法在我給它貼上標簽的行中工作,錯誤提示'Int'與'String'不相同 工作代碼是原始版本,無論我在“日期選擇器”中輸入什么內容,它都可以工作,它顯示用戶選擇的日期,因此,如果上午7:15,它將顯示為上午7:15,而不會減去任何內容。

與情節提要掛鈎的DatePicker

@IBOutlet weak var theDatePicker: UIDatePicker!

不帶.toInt()的原始代碼

func handler(sender: UIDatePicker) {
        var timeFormatter = NSDateFormatter()
        timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

        var strDate = timeFormatter.stringFromDate(theDatePicker.date)

        hoursLeftLabel.text = strDate

    }

修改后的代碼

func handler(sender: UIDatePicker) {
        var timeFormatter = NSDateFormatter()
        timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

        var intDate = timeFormatter.stringFromDate(theDatePicker.date).toInt()

        hoursLeftLabel.text = intDate

    }

如果您有任何疑問或需要任何澄清,請在下方評論

嘗試使用:

 hoursLeftLabel.text = "\(intDate)"

這應該起作用,因為您創建了一個包含int日期的字符串。

錯誤Int與字符串不同意味着您在需要字符串的地方傳遞了Int。 錯誤的確可以更精確,例如說出錯誤的類型或類似的內容

編輯:我建議您做這樣的日期計算:

let newDate = theDatePicker.date.dateByAddingTimeInterval(-5*60*60) //-5 Hours
//now you can display your date like this:
hoursLeftLabel.text = timeFormatter.stringFromDate(newDate)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM