ios - 为选定的单元格禁用 prepareForReuse

标签 ios objective-c uitableview custom-cell

我有一个自定义的 UITableViewCell。当一个单元格被选中时,一个 UILabel 被添加到它。我必须使用 prepareForReuse 以免变得困惑,如下所示:

- (void)prepareForReuse {
    NSArray *viewsToRemove = [self.view subviews];
    for (UILablel *label in viewsToRemove) {
        [label removeFromSuperview];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategorieCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    return customCell;
}

问题是,当我向下滚动到标签不可见,然后向上滚动时,标签不再存在。原因显然是因为当细胞被重复使用时,我删除了所有标签。

那么有没有办法为选定的行禁用prepareForReuse(或只是方法中的代码),如何实现?

最佳答案

滚动离开的单元格将被重复使用,并且没有办法绕过它。即使您避免使用removeFromSuperview逻辑,该单元格也会重新出现在不同的索引路径中,可能不是您想要的位置。

有条件地配置单元格的方法在cellForRowAtIndexPath中。在那里,您可以询问indexPath是否在 TableView 的indexPathsOfSelectedCells中。如果是,则使用额外的标签进行配置,如果不是,则不配置。

减少困惑的一种方法是让这些标签无条件保留在单元格中,只需将它们的 alpha 设置为 0 或 1,具体取决于选择状态。

例如,在

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    // if you know the table has singular selection
    NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
    BOOL rowIsSelected = [indexPath isEqual:selectedIndexPath];

    // OR, for multiple select...
    NSArray *selection = [tableView indexPathsForSelectedRows];
    BOOL rowIsSelected = [selection containsObject:indexPath];

    // now either conditionally create/destroy or show/hide the subviews
    // that appear on selection (I prefer show/hide for simpler cells)...

    [cell configAsSelected:rowIsSelected];  // have the custom cell do it

    // in that method, or here, if you're less OO-inclined...
    cell.subviewThatAppearsOnSelected.alpha = (rowIsSelected)? 1.0 : 0.0;

更重要的是,这是根据模型及其在表格中的当前位置可靠地配置单元格的建议位置

关于ios - 为选定的单元格禁用 prepareForReuse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28337041/

相关文章:

ios - Tableview Like Snapchat 发送功能(多选和可滑动标签)

iphone - 您可以将 UITableViewController TableView 添加到另一个 View 吗?

java - AWS appium ios 测试总是失败

iphone - 如何安全地使用最近才引入 iOS 的对象的属性?

ios - 将核心数据实体的子集映射为部分键路径

ios - TableView didSelect row 问题

ios - 自动布局不起作用?

ios - 修改webView的请求shouldStartLoadWithRequest :

ios - 如何关闭使用 presentModalViewController : 打开的 View Controller

objective-c - cocos2d - CCDirector,replaceScene 函数问题