Я пытаюсь позволить каждой ячейке иметь свое собственное «оставшееся время», имея возможность установить конкретное время обратного отсчета для каждой ячейки.
Я просмотрел этот ответ , иэто в значительной степени то, что я пытаюсь сделать, но вместо записи 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