我目前正在使用 Monotouch (Xamarin) 框架开发 iOS 应用。
我有一个自定义表格 View 源,它使用自定义单元格,其单元格高度是动态计算的。
当我在 iOS 模拟器中运行项目时,如果我快速滚动到底部或顶部,顶部的单元格会替换底部的单元格,反之亦然 - 就好像它绘制不正确,或者错误地重用了错误的单元格?
澄清一下——如果我的细胞是
一个 二 三 四 五个
如果我从上到下快速滚动,我的单元格显示为
一个 二 三 四 一个
或者,如果我缓慢滚动到底部,并且单元格保持有序,一旦我快速滚动到顶部,我就会得到
五 二 三 四 五个
如果我偶尔上下滚动,单元格可能会随机混合。
我的表源代码如下:
PostModel[] models;
string cellIdentifier = "FeedCell";
public FeedSource (PostModel[] items)
{
models = items;
}
public override int RowsInSection (UITableView tableview, int section)
{
return models.Length;
}
public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
FeedCell cell = this.GetCell (tableView, indexPath) as FeedCell;
var height = cell.height;
return height;
}
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
FeedCell cell = tableView.DequeueReusableCell (cellIdentifier) as FeedCell;
//if there are no cells to reuse, create a new one
if (cell == null) {
cell = new FeedCell (models [indexPath.Row], new NSString (cellIdentifier));
cell.LayoutSubviews ();
}
//cell.height = cell.height;
return cell;
}
我听说过动态单元格高度的性能问题,但我只测试了 5 个单元格,这看起来很奇怪。
会不会只是我的 iOS 模拟器,而这不会发生在设备上?有解决办法吗?
最佳答案
只要有可能,细胞就会被重复使用。逻辑是给我任何可用的单元格 (DequeueReusableCell
),如果没有可用的单元格 (cell == null
),则创建一个新单元格 (new FeedCell
)。
因此,您在创建单元格时不应固定单元格的内容。您只需创建一个新的空单元格。
在你有了一个单元格之后,你就可以在该单元格中填充该索引路径所需的内容。
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
FeedCell cell = tableView.DequeueReusableCell (cellIdentifier) as FeedCell;
//if there are no cells to reuse, create a new one
if (cell == null) {
cell = new FeedCell (new NSString (cellIdentifier));
}
cell.model = models[indexPath.row]; // assuming you can do something like this.
cell.layoutSubviews();
return cell;
}
关于iOS - UITableView - 快速滚动时行神秘地重复自己? (模拟器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21841986/