简体   繁体   English

不要在 UITableView 中重用单元格

[英]Don't reuse cell in UITableView

let cell = tableView.dequeueReusableCellWithIdentifier("cellReuseIdentifier", forIndexPath: indexPath) as! CustomTableViewCell

一旦创建单元格,我不想重用单元格,我希望它在内存中可用。

It's your decision of course, but it's a very bad idea.这当然是你的决定,但这是一个非常糟糕的主意。 Unless you have less than 10 cells in your tableView and you are 100% sure there will be no more cells.除非您的tableView单元格少于 10 个,并且您 100% 确定不会有更多的单元格。 Otherwise the app will crash on memory pressure pretty fast.否则应用程序会很快因内存压力而崩溃。

Just don't dequeue cells.只是不要dequeue单元格。 Create new each time:每次创建新的:

let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "CellReuseIdentifier")

Not recommended, but it's your decision after all.不推荐,但毕竟这是你的决定。


A note about most recent swift versions:关于最新 swift 版本的说明:

' UITableViewCellStyle ' has been renamed to ' UITableViewCell.CellStyle ' UITableViewCellStyle ”已重命名为“ UITableViewCell.CellStyle

If you have limited number of cell then only you should use this method如果您的单元格数量有限,则只能使用此方法

On viewDidLoad() you can create NSArray of custom cell在 viewDidLoad() 上,您可以创建自定义单元格的 NSArray

 self.arrMainCell.addObject(your custom cell);

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.arrMain.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = self.arrMain.objectAtIndex(indexPath.row)

 }

Don't use a tableview.不要使用表格视图。 Just use a scrollview.只需使用滚动视图。 Use tableview if you have a long list where you can't keep all the views in memory.如果列表很长,无法将所有视图保存在内存中,请使用 tableview。

When you need a cell object at runtime, call the table view's dequeueReusableCell(withIdentifier:for:) method, passing the reuse identifier for the cell you want.当你在运行时需要一个单元格对象时,调用表视图的 dequeueReusableCell(withIdentifier:for:) 方法,传递你想要的单元格的重用标识符。 The table view maintains an internal queue of already-created cells.表视图维护一个已创建单元的内部队列。

If the queue contains a cell of the requested type, the table view returns that cell.如果队列包含请求类型的单元格,则表视图返回该单元格。 If not, it creates a new cell using the prototype cell in your storyboard.如果没有,它会使用故事板中的原型单元格创建一个新单元格。 Reusing cells improves performance by minimizing memory allocations during critical times, such as during scrolling.重用单元格通过在关键时间(例如滚动期间)最小化内存分配来提高性能。

If you change the appearance of your custom cell's views, implement the prepareForReuse() method of your cell subclass.如果您更改自定义单元格视图的外观,请实现单元格子类的 prepareForReuse() 方法。 In your implementation, return the appearance of your cell's views to their original state.在您的实现中,将单元格视图的外观恢复到其原始状态。 For example, if you change the alpha property of a view in your cell, return that property to its original value例如,如果您更改单元格中视图的 alpha 属性,请将该属性返回到其原始值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM