尝试将计时器设置为在tableViewCell内的标签上显示时间。
由于我缺乏知识,我面临着这个问题。
我熟悉Timer,但我可以找到最有效的方法。
非常感谢
这是我的代码
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
}
这里我正在加载tableView
(
答案 0 :(得分:0)
首先在单元格中添加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
}
希望这有帮助
答案 1 :(得分:0)
我会向单元格本身添加一个Timer,每秒重新计算一次。
class WeatherCellLocationCell: UITableViewCell {
@IBOutlet weak var localTime: UILabel!
@IBOutlet weak var cityName: UILabel!
@IBOutlet weak var currentTemp: UILabel!
var timer: Timer?
var weatherPlace: WeatherPlaceData?
func configureCell(weatherPlace : WeatherPlaceData){
self.weatherPlace = weatherPlace
setTime()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(WeatherCellLocationCell.setTime), userInfo: nil, repeats: true)
}
func setTime() {
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)
}
override func prepareForReuse() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
}