我试图通过为每个单元格设置特定的倒数时间,让每个单元格都有自己的“剩余时间”。
我查看了this answer,这几乎是我要尝试的工作,但是我可能会从数据源获取值并将其与值相对应,而不是编写cell.expiryTimeInterval = 10索引。
首先,我还没有从答案中得到计时器的帮助。我已经尝试过RunLoop.current.add(timer!, forMode: .common)
,并且一切似乎都正确。我无法对该线程发表评论,因为我没有足够的代表,所以我要发表一个新帖子。
这是我的自定义单元格类的相关部分:
private var timer: Timer?
private var timeCounter: Double = 0
var expiryTimeInterval: TimeInterval? {
didSet {
startTimer()
}
}
let timeLabel: UILabel = {
let tl = UILabel()
tl.translatesAutoresizingMaskIntoConstraints = false
tl.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
tl.textColor = .black
return tl
}()
func set(content: Item) {
self.expiryTimeInterval = content.time
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupCell()
}
private func startTimer() {
if let interval = expiryTimeInterval {
timeCounter = interval
if #available(iOS 10.0, *) {
timer = Timer(timeInterval: 1.0,
repeats: true,
block: { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.onComplete()
})
} else {
timer = Timer(timeInterval: 1.0,
target: self,
selector: #selector(onComplete),
userInfo: nil,
repeats: true)
}
}
}
@objc func onComplete() {
guard timeCounter >= 0 else {
timer?.invalidate()
timer = nil
return
}
timeLabel.text = String(format: "%d", timeCounter)
timeCounter -= 1
}
func setupCell() {
self.contentView.addSubview(timeLabel)
let labelInsets = UIEdgeInsets(top: 16, left: 16, bottom: -16, right: -16)
let timeLabelConstraints = [
timeLabel.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: labelInsets.left),
timeLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: labelInsets.top),
timeLabel.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: labelInsets.right),
timeLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: labelInsets.bottom)
]
NSLayoutConstraint.activate(stackViewConstraints)
}
“项目”是我的模型,其中包含TimeInterval