uitableview - 单点触控 : The correct way to reuse a UITableViewCell

标签 uitableview xamarin.ios reusability

我正在找出在 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 值),执行一些其他操作 - 从服务中获取其他一些数据 - 和 然后使用新值 再次更新该单元格。在这种情况下,每个单元格都必须是唯一的。

所以,我的问题是:

这是重用单元的正确方式,还是有可能想出另一种解决方案来重用单元并保证单元的每个抽头都是唯一的?

我希望一切都清楚:) 在此先感谢您。问候。

最佳答案

我觉得你在这里做的有点太多了。特别是您在字典中保存对单元格的额外引用的部分。

我会以不同的方式去做。 DequeueReusableCell 方法在那里,以便您可以检索任何现有单元格,但不一定是它包含的值。所以这样的事情就足够了:

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{

    int rowIndex = indexPath.Row;
    Item item  = _listOfItems[rowIndex];

    UITableViewCell cell = tableView.DequeueReusableCell(_cID);

    if (cell == null)
    {
        cell = new UITableViewCell(UITableViewCellStyle.Value1, _cID);
    }

    // Store what you want your cell to display always, not only when you are creating it.
    cell.Tag = item.ID;
    cell.TextLabel.Text = item.Title;

    return cell;
}

然后,在 RowSelected 方法中,更改您的数据源:
public override void RowSelected (UITableView tableView, NSIndexPath indexPath){
    // Do something here to change your data source _listOfItems[indexPath.Row] = new Item();
}

如果我正确理解您想要做什么,则此解决方案更好。

关于uitableview - 单点触控 : The correct way to reuse a UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5686001/

相关文章:

ios - 添加到收藏夹功能[swift]

c# - Task<T> 异步导致 Xamarin.iPhone (MonoTouch) JIT 错误?

c# - 在带有身份验证的 MonoTouch 中使用 WCF 服务

iphone - 如何存储 CALayers 以便重复使用?

reusability - 提高代码可重用性的因素

testing - 清洁代码、测试和重用性说明

ios - 即使使用不同的单元格样式,UITableViewCell detailTextLabel也不会显示

iOS - 在滚动之前移动 TableView

json - 在 Swift 中使用来自 Rest API 的数组填充 UITableview

c# - 在我自己的 "UITableViewController"中使用默认实现使方法可选