我正在构建一个日历应用程序,其中某人的空闲时间将以短消息和三个不同图像中的一个作为此单元格的背景突出显示。
每次细胞离开屏幕时停止更改图像的最佳方法是什么? 这个逻辑应该在UITableViewCell中吗?
class FreeTimeCell: UITableViewCell {
@IBOutlet weak var background: UIImageView!
@IBOutlet weak var freeTimeMessage: UILabel!
@IBOutlet weak var freeTimePeriod: UILabel!
@IBOutlet weak var freeTime: UILabel!
var timeblock: Timeblock! {
didSet {
self.freeTimePeriod.text = "\(timeblock.startTime.dateToString()) - \(timeblock.endTime.dateToString())"
self.freeTime.text = "OccupiedTime.FreeTime".localized
self.freeTimeMessage.text = MessagesInteractor.getFreetimeTimeblock()
let randomNumber = arc4random_uniform(3)
let imageName = "freetime\(randomNumber)"
self.background.image = UIImage(named: imageName)
}
}
override func awakeFromNib() {
super.awakeFromNib()
//removes highlighting of the cell when tapping on it
self.selectionStyle = UITableViewCellSelectionStyle.none
}
TableViewController
/**
Checks which data cell type belongs to this cell, and returns correct table cell accordingly
*/
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch self.dataCells[indexPath.row].cellType {
case .ConflictHeader, .TimeToFirstMeetingHeader :
return self.generateHeaderCell(indexPath: indexPath)
case .FreeTime:
return self.generateFreeTimeCell(indexPath: indexPath)
case .SingleMeeting:
return self.generateSingleMeetingCell(dataCell: self.dataCells[indexPath.row], indexPath: indexPath)
}
}
/**
Generates Free Time Cell (between meetings to show user free spot)
- parameter indexPath: used to dequeue the reusable cell
- returns: Free time cell generated
*/
private func generateFreeTimeCell(indexPath: IndexPath) -> FreeTimeCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "FreeTimeCell", for: indexPath) as! FreeTimeCell
cell.timeblock = self.dataCells[indexPath.row].timeblock
return cell
}
答案 0 :(得分:2)
目前,在为单元格设置样式时,您使用随机数来确定单元格的背景。相反,将此逻辑拉出单元格并进入tableview。如果你这样做,那么你可以跟踪你正在使用的图像,并设置正确的图像到单元格,以便在滚动时保持一致。
在您的情况下,您可以在Timeblock类中添加另一个变量来设置图像编号或图像名称,并使用它来加载单元格中的图像。