gpt4 book ai didi

ios - iOS 中 UITableView 的每个单元格的时间倒计时

转载 作者:可可西里 更新时间:2023-11-01 00:20:42 24 4
gpt4 key购买 nike

我想在 tableview 的每个单元格上显示倒数计时器。

步骤

我有来自服务器的报价列表和过期时间。所以在那之后我想用 UITableView 上的每个单元格显示这个过期倒数计时器。

我正在做这样的事情。但没有结果。

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TimeCell
cell.expiryTimeInterval = 2

return cell



}

**我开始计时的单元格类。仅打印 Step1 和 Step2 **

class TimeCell: UITableViewCell {

@IBOutlet weak var myLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()

}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

}

private var timer: Timer?
private var timeCounter: Double = 0

var expiryTimeInterval : TimeInterval? {
didSet {
startTimer()
print("Step 1 \(expiryTimeInterval!)")
}
}

private func startTimer() {
if let interval = expiryTimeInterval {
timeCounter = interval
print("Step 2 \(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,
target: self,
selector: #selector(onComplete),
userInfo: nil,
repeats: true)
}
}
}

@objc func onComplete() {

print("Step 3")
guard timeCounter >= 0 else {
timer?.invalidate()
timer = nil
return
}
myLabel.text = String(format: "%d", timeCounter)
timeCounter -= 1
}

}

最佳答案

我宁愿建议您创建一个自定义单元格,并在该单元格类中,根据您从服务器获得的值创建一个计时器。这样每个单元格都会有自己的计时器。这就是你可能想要的。在您当前的实现中,您的计时器处理程序不知道单元格或其行号。

class MyCustomCell: UITableViewCell {
@IBOutlet weak private var myLabel: UILabel!

private var timer: Timer?
private var timeCounter: Double = 0

var expiryTimeInterval: TimeInterval? {
didSet {
startTimer()
}
}

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
}
myLabel.text = String(format: "%d", timeCounter)
timeCounter -= 1
}
}

用法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyCustomCell

cell.expiryTimeInterval = 10

return cell
}

转到单元格 nibstoryboard 并将 TimeCell 的类名更改为 MyCustomCell

关于ios - iOS 中 UITableView 的每个单元格的时间倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48221818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com