尝试设置计时器以在 tableViewCell 内的标签上显示时间。
由于我缺乏知识,我面临着这个问题。
我熟悉 Timer,但我可以找出最有效的方法。
非常感谢
这是我的代码
import UIKit
class WeatherCellLocationCell: UITableViewCell {
@IBOutlet weak var localTime: UILabel!
@IBOutlet weak var cityName: UILabel!
@IBOutlet weak var currentTemp: UILabel!
func configureCell(weatherPlace : WeatherPlaceData){
localTime.text = DateFormatter.localizedString(from: weatherPlace.localDate, dateStyle: .none, timeStyle: .short)
cityName.text = weatherPlace.name
let temp = Int(weatherPlace.currentTemp)
currentTemp.text = "\(temp)"
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
这里我正在加载tableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCellLocation", for: indexPath) as! WeatherCellLocationCell
let place = fetchedResultsController.object(at: indexPath)
// var timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTime), userInfo: indexPath, repeats: true)
cell.configureCell(weatherPlace: place)
return cell
}
最佳答案
首先在您的单元格中添加WeatherPlaceData
对象并将计时器放入您的单元格
var currentWeatherPlaceData: WeatherPlaceData?
fileprivate var timeWorking : Bool = false
var timer:Timer?
添加更新标签的方法
func updateTime()
{
localTime.text = DateFormatter.localizedString(from: self.currentWeatherPlaceData.localDate, dateStyle: .none, timeStyle: .short)
}
将您的 configureCell
方法更改为此方法
func configureCell(weatherPlace : WeatherPlaceData){
self.currentWeatherPlaceData = weatherPlace
if(!timeWorking)
{
localTime.text = DateFormatter.localizedString(from: self.currentWeatherPlaceData.localDate, dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
self.timeWorking = true
}
cityName.text = weatherPlace.name
let temp = Int(weatherPlace.currentTemp)
currentTemp.text = "\(temp)"
}
最后调整重用准备以避免问题,重新启动计时器
override func prepareForReuse() {
super.prepareForReuse()
self.timer.invalidate()
self.timeWorking = false
}
希望对你有帮助
关于ios - 在 UITableViewCell 中使用 Timer 在 UILabel 中设置时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45524341/