当我想在uitableview单元格中使用计时器时遇到问题。 每次当我滚动到底部,然后再次向上重置计数器的原始值。XCode Swift Timer在滚动时在tableview中重新加载
我知道问题是什么..当滚动回来时,单元格被重新加载。但我怎么能实现单元格不滚动上下滚动时,因此我可以保留原单元格重新加载。任何伪代码都会有所帮助。
我的代码看起来像这样。
FirstViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(hexString: "#bde8fb")
parseXhr(offset,limit:limit)
self.timer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(FirstViewController.fireCellsUpdate), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// algemene cell gegevens
let cell = self.tv.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
let separator = UIView(frame: CGRectMake(0, 0, cell.bounds.size.width, 20))
separator.backgroundColor = UIColor(hexString: "#bde8fb")
cell.contentView.addSubview(separator)
cell.photo.setBottomBorder("#bde8fb")
cell.timeInterval = self.timercounter[indexPath.row]
// load the image
cell.photo.contentMode = UIViewContentMode.ScaleAspectFit
cell.photo.kf_setImageWithURL(NSURL(string:"\(Config.image_dir)\(imageUrlArray[indexPath.row])"),placeholderImage: UIImage(named: Config.lazyLoadImage))
// set the product name
cell.veiling_title.text = productNameArray[indexPath.row]
cell.veiling_title.textAlignment = .Center
return cell
}
func fireCellsUpdate() {
let notification = NSNotification(name: "CustomCellUpdate", object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
而且我CustomCell.swift看起来像这样
var timercounter = 0
@IBOutlet var veiling_title: UITextView!
@IBOutlet var photo: UIImageView!
@IBOutlet var veilingSeconds: UILabel!
var timeInterval: Int = 0 {
didSet {
self.veilingSeconds.text = "\(timeInterval)"
}
}
func updateUI() {
if self.timeInterval > 0 {
self.timeInterval -= 1
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(CustomCell.updateUI), name: "CustomCellUpdate", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
您需要更新模型('timercounter')在每次'timeInterval'改变以保持模型和视图同步时,在特定的索引路径上。 – vadian
谢谢!,你有我的代码片段吗?我必须在FirstViewController.swift中更新这个吗? – erwinnandpersad
在'cellForRowAtIndexPath'中,我将索引路径(该行足够)传递给单元格。然后你就可以直接从单元更新'timercounter'数组中的计数器。如果'timercounter'是值类型,不要忘记将更改的值分配回数组。 – vadian