【问题标题】:How would I change the date when pressing a button?按下按钮时如何更改日期?
【发布时间】:2015-09-03 23:27:29
【问题描述】:

我正在使用 NSDate,我得到了要显示的日期,它使用 iphone 时间更改它。我现在在按下按钮时无法更改日期,无论是更早还是第二天。我需要它像在健身应用程序中一样,它们有两个箭头,你可以按左边的箭头去上一个日期,按右边的箭头去第二天。我该怎么做?这是我现在拥有的代码:

    override func didMoveToView(view: SKView) {

    dateLabel.zPosition = 22
    dateLabel.fontName = "Krungthep"
    dateLabel.fontColor = UIColor.whiteColor()
    dateLabel.fontSize = 17
    dateLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.FullStyle, timeStyle: NSDateFormatterStyle.NoStyle)
    dateLabel.position = CGPointMake(self.size.width / 2.0, self.size.height / 1.1)
    self.addChild(dateLabel)

   }

       override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

    var touch: UITouch = touches.first as! UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)

            if node.name == "next" {
             //next day

              }







    if node.name == "before" {

        //previous day 
        let earlyDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitDay,value: -1,toDate:
            NSDate(),options: NSCalendarOptions.WrapComponents)
        date.earlierDate(earlyDate!)


    }

【问题讨论】:

    标签: ios swift nsdate


    【解决方案1】:

    看看NSCalendar。具体来说,在 Xcode 文档中搜索“日历计算”。

    您将要获取当前日历,然后创建一个 NSDateComponents 对象,将其日期值设置为 1 或 -1,然后使用方法 dateByAddingComponents:toDate:options 在您的日期中增加或减少一天。

    【讨论】:

    • 当我按下按钮转到之前没有更改的日期时,您能看看我更新的代码吗?
    • 您发布的代码将如何对您显示的日期进行任何更改? (回答,它不能。)您正在创建一个新日期,然后调用 date.earlierDate 并忽略结果。你的代码基本上什么都不做。
    • 所以我猜我必须更改日期标签??
    • 如果您有一个包含日期的标签,并且您想显示一个不同的日期,那么您是否需要更改该标签?
    • 是的,我将使用 stringFromDate。
    猜你喜欢
    • 2020-01-28
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多