【发布时间】:2011-08-06 20:36:53
【问题描述】:
我正在找出在 UITableView 中重用单元格的正确方法,并且我会知道我使用的机制是否正确。
场景如下。
我有一个 UITableView,它显示从 Web 服务获取的数据列表。
_listOfItems = e.Result as List<Item>;
其中 _listOfItems 是一个实例变量。
这个列表被传递给一个扩展 UITableViewSource 的类。显然这个类重写了 GetCell 方法以这种方式可视化数据:
public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(_cID);
Item item = _listOfItems[indexPath.Row];
int id = item.Id;
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Value1, _cID);
cell.Tag = id;
_cellControllers.Add(id, cell);
}
else
{
bool vb = _cellControllers.TryGetValue(id, out cell);
if(vb)
{
cell = _cellControllers[id];
}
else
{
cell = new UITableViewCell(UITableViewCellStyle.Value1, _cID);
cell.Tag = id;
_cellControllers.Add(id, cell);
}
}
cell.TextLabel.Text = item.Title;
return cell;
}
在哪里
_cID 是单元格的实例变量标识符
string _cID = "MyCellId";
_cellControllers 是一个字典,用于存储单元格和 Item 实例的相对 id
Dictionary<int, UITableViewCell> _cellControllers;
我正在使用字典来存储单元格,因为当点击一行时,我必须检索所点击单元格的 ID(通过 cell.Tag 值),执行一些其他操作 - 即从服务中检索其他一些数据- 然后用新值再次更新该单元格。在这种情况下,每个单元格都必须是唯一的。
所以,我的问题是:
这是重用单元格的正确方式,还是有可能找到另一种解决方案来重用单元格并保证单元格的每次点击都是唯一的?
我希望一切都清楚:) 提前谢谢你。问候。
【问题讨论】:
标签: uitableview xamarin.ios reusability