![](/img/trans.png)
[英]How do I make my table view's cell selection based on a stepper value, not the physical selection of the cell in swift 3?
[英]How do I make my table view less laggy in Swift?
我的目标是在表格视图中为每一行简单显示唯一的图像和标签。 我目前在这里:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath )-> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! DailyBarCellViewTableViewCell
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0)) {
let data = DailyBarCellViewTableViewCell.Static.data
dispatch_async(dispatch_get_main_queue()) {
cell.barName?.text = data.namesArray[indexPath.row]
}
}
return cell
}
CellDataDisplayInformation的内容:
struct CellDataDisplayInformation {
var namesArray : [String?] = []
var pictureArray : [UIImage?] = []
init(){
for index in 0...21 {
var data = BarDetails(index: index)
if data.barName != nil && data.barImage != nil {
namesArray.append(data.barName!)
pictureArray.append(data.barImage!)
}
}
}
}
data = CellDataDisplayInformation()
包含[Strings?]和[UIImages?]的数组,分别在每个单元格中显示。 通过这种方法,UI最初会在每个单元格中加载所有正确的信息。 但是,当我向下滚动到看不见的单元格时,每个单元格中的标签会随机播放2秒钟,然后移至它们的正确位置。
如果我不使用“调度”,那就去做:
let data = CellDataDisplayInformation()
cell.barName?.text = data.namesArray[indexPath.row]
每个单元格的所有标签均保持不变,并且不会随机播放,但是当我在每个新单元格上滚动时,视图会滞后。
因此,总之,在表单元格中显示数据时如何避免乱码和滞后?
我的DailyBarCellViewTableViewCell类:
class DailyBarCellViewTableViewCell: UITableViewCell {
// MARK: Properties
struct Static {
static var data = CellDataDisplayInformation()
}
@IBOutlet weak var barName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.barName.text = nil
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse() {
self.barName.text = nil
super.prepareForReuse()
}
}
在您返回-cellForRowAtIndexPath
的cell
后, dispatch_async
调用会导致cell.barName?.text = data.namesArray[indexPath.row]
被执行。 您不应该这样做,因为在获取数据时,这些单元格可能已经被重新用于其他行。
无需在该特定cell
上设置文本,而是需要让表为要为其获取数据的索引出售一个单元格。 如果在获取数据时该索引仍在屏幕上,则tableView将为您提供正确的单元格。 否则,返回nil。
像这样:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! DailyBarCellViewTableViewCell
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0)) {
let data = CellDataDisplayInformation()
dispatch_async(dispatch_get_main_queue()) {
//do it this way
if let futureCell = tableView.cellForRowAtIndexPath(indexPath) as? DailyBarCellViewTableViewCell {
futureCell.barName?.text = data.namesArray[indexPath.row]
}
}
}
return cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.