【发布时间】:2020-08-13 23:49:37
【问题描述】:
我目前正在学习编写 swift 应用程序,并正在尝试自己做一些项目。我目前的个人挑战是做一个倒数计时器应用程序。这个概念很简单:用户从 UIDatePicker 输入一个日期,然后应用程序显示距离他的各种事件列表的剩余时间(使用用户默认值将事件保存在内存中)。所有上述事件都显示在集合视图中(请参阅下面的屏幕截图)。
我遇到了一些对我的实际技能来说太复杂的问题,我想你们可能会有答案,或者至少有一些建议!这是我的问题:我希望今天和事件之间的剩余时间每秒减少,并通过 collectionViewCell 内的标签显示。我找到了一种非常简单的方法来做到这一点,有一个计时器,但是用 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 forItemAt 函数中实现它的方式:
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)
我尝试了所有我能想到的方法,但现在遇到了障碍。我的项目中还有很多事情要解决,所以我还没有完全停止。如果您需要更多代码行和/或精度,请告诉我,我会为您提供您认为有帮助的任何内容。
非常感谢您抽出宝贵时间查看我的问题,
路易·G
【问题讨论】:
标签: swift timer uicollectionview label uicollectionviewcell