Mah*_*aha 3 arrays uitableview ios swift
我有一个tableView来显示工作日的时间
timingsArray在tableView中用于显示时序
timingsArray类型timingObj
class timingObj {
var dayNo: Int?
var open: String?
var close: String?
var dayName: String?
init(json: JSON){
// to take data from json
}
init(name: String, number: Int){
self.dayName = name
self.dayNo = number
}
}
Run Code Online (Sandbox Code Playgroud)
在tableView中我想显示所有日期及其时间,如果当天没有时间,则计时单元格将为空
let cell = tableView.dequeueReusableCellWithIdentifier("TimingsCell", forIndexPath: indexPath) as! timingCell
let timings = self.Details!.timingsArray
let dayTime = timings[indexPath.row]
cell.dayLabel.text = dayTime.dayName
if dayTime.open != nil && dayTime.close != nil {
cell.timeLabel.text = "\(convertTimeFormat(dayTime.open!)) - \(convertTimeFormat(dayTime.close!))"
}
return cell
Run Code Online (Sandbox Code Playgroud)
这是细胞的类
class timingCell: UITableViewCell {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
}
Run Code Online (Sandbox Code Playgroud)
例如星期二和星期四只有时间
问题是当我向上和向下滚动时,周二的定时值在周三重复,当我继续滚动时,定时值在其他单元格中也会重复
有任何想法吗?先感谢您
您应该prepareForReuse在自定义单元类中实现,您可以在其中重置需要重置的内容.例如:
class timingCell: UITableViewCell {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
func prepareForReuse() {
super.prepareForReuse()
cell.timeLabel.text = nil
cell.dayLabel.text = nil
}
}Run Code Online (Sandbox Code Playgroud)
prepareForReuse在您将单元格重置为初始状态的单元格类中添加方法与@CH Uck的答案具有相同的效果
例如:
func prepareForReuse() {
super.prepareForReuse()
self.dayLabel.text = ""
self.timeLabel.text = ""
}
Run Code Online (Sandbox Code Playgroud)
另请参阅:
prepareForReuse Apple开发人员文档.
来自Apple Docs:
在运行时,表视图将单元对象存储在内部队列中.当表视图要求数据源配置要显示的单元对象时,数据源可以通过向表视图发送dequeueReusableCellWithIdentifier:消息来传入排队对象,并传入重用标识符.数据源在返回之前设置单元格的内容和任何特殊属性.这种单元对象的重用是一种性能增强,因为它消除了单元创建的开销.
因此,在重用队列中的单元格时,您正在执行的操作是检索已创建和配置的单元格.对创建的单元格所做的更改也将应用于重用的单元格,这些单元格在重新使用的单元格不再可见时立即滚动显示.这意味着您必须重新分配要覆盖的任何值,这些值是您要显示的唯一单元格的自定义,如果没有要显示的内容/空字符串,这也适用.否则,您将获得随机的结果.
let cell = tableView.dequeueReusableCellWithIdentifier("TimingsCell", forIndexPath: indexPath) as! timingCell
let timings = self.Details!.timingsArray
let dayTime = timings[indexPath.row]
cell.dayLabel.text = dayTime.dayName
if dayTime.open != nil && dayTime.close != nil {
cell.timeLabel.text = "\(convertTimeFormat(dayTime.open!)) - \(convertTimeFormat(dayTime.close!))"
}
else{
//change label to empty string when reusing
cell.timeLabel.text = "";
}
return cell
Run Code Online (Sandbox Code Playgroud)