ios - tableviewcell重复uibuttons

标签 ios swift uitableview uibutton

我在使用桌面 View 上的按钮时遇到了一些问题。

我有一个用 3 个按钮自定义的 tableViewCell。我将按钮设置为隐藏在界面生成器中,当表格加载时,按钮会按预期隐藏。

然后,当调用 didSelectRow 时,我将 tableview 的隐藏属性设置为 false ;当调用 didDeselectRow 时,将 tableview 的隐藏属性设置为 hide.true 。这也很好用。问题是在 didSelectRow 中设置为可见的按钮也每七个单元格下方可见。他们不断重复自己。

下面是显示按钮的代码

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   let cell = tableView.cellForRowAtIndexPath(indexPath) as! ContactsViewCell

            print("Table selected")

                cell.insertEmailButton.hidden = false
                cell.insertPhoneButton.hidden = false
                cell.insertAllButton.hidden = false
                cell.contactTextLabel.alpha = 0.2
                cell.contactDetailTextLabel.alpha = 0.2
        }

当取消选择 tableViewCell 时,这会隐藏它们

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! ContactsViewCell

        cell.insertEmailButton.hidden = true
        cell.insertPhoneButton.hidden = true
        cell.insertAllButton.hidden = true
        cell.contactTextLabel.alpha = 1.0
        cell.contactDetailTextLabel.alpha = 1.0  
    }

我做了一些研究,我了解到这可能是buttons.hidden 设置为 false 的行被 TableView 重用。但我从文档中了解到,被重用的单元格来自 cellForRowAtIndexPath,而不是 didSelectRow 的单元格,这是我将 button.hidden 设置为 false 的地方。

我还尝试在 cellForRowAtIndexPath 的 if else 语句中使用 cell.isSelected 属性来隐藏和显示按钮,但这根本不显示按钮。

预先感谢您的帮助

最佳答案

当表格滚动时,表格 View 会重用单元格的 View ,以节省内存。因此,例如,当您将按钮设置为可见(在 didSelectRow 内),然后向下滚动表格时,表格 View 将获取顶部可见屏幕之外的单元格,并在底部重用它们,以保存创建新单元的开销,提高性能。

这就是为什么您之前的单元格属性会重复。

要在滚动单元格上获得所需的隐藏按钮,我建议在

中将button.hidden设置为true/false
tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

每当新行滚动到可见 View 区域时,这会将按钮设置为隐藏。

希望这有帮助。

关于ios - tableviewcell重复uibuttons,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545030/

相关文章:

android - 如何创建跨平台 Xamarin 移动应用程序项目?

ios - 使用 swift 和 UIViewAnimation 逐渐填充形状?

ios - ARC 转换失败 : -ccc-arcmt-check argument "unused"

iOS:单击单元格时展开单元格

ios - 在 iOS 中每秒更新一次 TableView 中单元格中标签的文本

ios - 如何使用 Swift 在 iOS 中检测多行键盘粘贴事件?

ios - 在核心数据中使用类和点表示法访问是否会获得可变集?

ios - Swift - 在 PageViewController 场景中隐藏标签栏

ios - 不同版本的 iOS 上的 EXC_BREAKPOINT

swift - 无法将类型 'Int' 的值转换为预期的参数类型 'ClassName'