具有collectionViewCell.label.text使用计时器每秒更改一次



我目前正在学习编写swift应用程序的代码,并尝试自己做一些项目。我目前的个人挑战是做一个倒计时应用程序。这个概念很简单:用户从UIDatePicker输入日期,应用程序显示到他列出各种事件为止的剩余时间(使用用户默认值将事件保存在内存中(。所有上述事件都显示在集合视图中(请参阅下面的屏幕截图(。

我遇到了一些对我的实际技能来说太复杂的事情,我想你们可能会有答案,或者至少有一些建议!这是我的问题:我希望从今天到活动之间的剩余时间每秒钟都减少一次,并通过集合ViewCell中的标签显示我找到了一个非常简单的方法,使用计时器,但用collectionViewCell实现上述解决方案让我非常头疼。

以下是我想分享的代码摘录,希望已经足够了:

@objc func UpdateTimeLabel(index: Int) -> String {

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.timeZone = userCalendar.timeZone

let date = dateFormatter.date(from: UserDefaults.standard.array(forKey: "dates")![index] as! String)!

let timeLeft = userCalendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: date)
return "(timeLeft.day!) days (timeLeft.hour!) hours (timeLeft.minute!) minutes (timeLeft.second!) seconds"

}

这是我的职责,我想每秒钟都激发它。它目前的制作方式是,其名为index的属性是collectionViewCell的indexPath.row。它引用存储为UserDefaults的事件日期数组。collectionView中的单元格数量与数组中的事件数量相同。

请参阅下面我在collectionView for ItemAt函数中实现它的方式:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

// Configure the state of the cell based on the propertires of the card if reprensents
let cardCell = cell as? EventCollectionViewCell

// UI Configuration
cardCell?.eventTitleLabel.text = ((UserDefaults.standard.array(forKey: "events")![indexPath.row]) as! String)

cardCell?.eventDateLabel.text = ("Event on: " + "((UserDefaults.standard.array(forKey: "dates")![indexPath.row]) as! String)")
cardCell?.countdownLabel.text = UpdateTimeLabel(index: indexPath.row)

cardCell?.eventView.layer.cornerRadius = 10

}

实际结果是,每个单元格都显示从今天到事件之间的剩余时间。这已经超出了我自己的想象!!!

实际代码的结果

我认为你们中的一个人可能会介入,帮助我回答这个问题:应该把一个看起来像下面代码的计时器放在哪里,以便每秒更新cardCell.countdownLabel.text

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTimeLabel), userInfo: nil, repeats: true)

我想尽了一切办法,现在遇到了障碍。在我的项目中,我还有很多事情要解决,所以我还没有完全停止。如果你需要更多的代码行和/或精度,请告诉我,我会为你提供任何你认为有用的东西。

非常感谢你花时间回顾我的问题,

Louis G

将此方法UpdateTimeLabel方法添加到EventCollectionViewCell中,并修改类似的方法

@objc func UpdateTimeLabel() {
let userCalendar = Calendar(identifier: .indian)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.timeZone = userCalendar.timeZone

let date = dateFormatter.date(from: UserDefaults.standard.array(forKey: "dates")![index] as! String)!

let timeLeft = userCalendar.dateComponents([.day, .hour, .minute, .second], from: Date(), to: date)
countdownLabel.text = "(timeLeft.day!) days (timeLeft.hour!) hours (timeLeft.minute!) minutes (timeLeft.second!) seconds"

}

完成此操作后,在EventCollectionViewCell中添加属性index,并在EventCollectionViewCell中的索引触发计时器的didSet上添加属性,例如:

var index: Int {
didSet {
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTimeLabel), userInfo: nil, repeats: true)
timer.fire()
}
}

更换

cardCell?.countdownLabel.text = UpdateTimeLabel(index: indexPath.row)

带有

cardCell?.index = indexPath.row

我发现了@Satyen建议的解决方案不起作用的原因!好吧,我知道,距离他上次回答已经快一个月了,但我不得不说,当我看到它没有修复我的应用程序时,我非常沮丧,并决定从事其他项目,希望其他人能加入进来,同时提供另一个解决方案。无论如何,今天早上我决定通过几次会议来找到这个问题,我很自豪地报告我做到了!

好的,下面是问题所在:我使用了一个名为";当前日期";就像今天一样。这个变量是在UpdateTimeLabel函数外部声明的,并在浴缸右侧的dateComponents中转换。结果:当前日期不是每秒刷新一次,因此每次将事件的日期与currentDate进行比较时,结果都保持不变。

这是工作代码:

@objc func UpdateTimeLabel() {
let userCalendar = Calendar.current
let todayDate = Date()
let components = userCalendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: todayDate)
let currentDate = userCalendar.date(from: components)!

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
dateFormatter.timeZone = userCalendar.timeZone
let date = dateFormatter.date(from: UserDefaults.standard.array(forKey: "dates")![index] as! String)!
let timeLeft = userCalendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: date)
countdownLabel.text = "(timeLeft.day!) days (timeLeft.hour!) hours (timeLeft.minute!) minutes (timeLeft.second!) seconds"
if currentDate >= date {
countdownLabel.text = "Cheers! This event has occured already."
print("An event expired.")
}
}

由这个var指数激发,正如@Satyen:所建议的那样

var index: Int = 0 {
didSet {

timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(UpdateTimeLabel), userInfo: nil, repeats: true)
timer.fire()
print("timer fired")

}
}

现在一切都如预期般运转!我仍然有一些效率调整,使我的代码更简单,但总的来说,它现在显示剩余的时间,并每秒钟减少一次!太激动了!!

再次感谢@Satyen的宝贵投入!

最新更新