當我想在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