【问题标题】:IOS UITableView display first 5 rows of an arrayIOS UITableView显示数组的前5行
【发布时间】:2021-05-06 17:29:16
【问题描述】:

我有一个带有 1 个单元格的 UITableView,当加载数组时,我只想让用户看到前 5 行的内容并模糊其余部分。因此,如果有一个包含 20 个项目的数组,则前 5 个需要可见,其余 15 个需要模糊。使用下面的代码,我只能在第 5 行添加模糊,我无法弄清楚。非常感谢任何帮助。

视图控制器

let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))



    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
        cell.cellLbl?.text = array[indexPath.row]

        if indexPath.row == 5 {
            visualEffectView.frame = cell.bounds
            visualEffectView.layer.masksToBounds = true
            cell.addSubview(visualEffectView)
        }
        return cell
    } 

【问题讨论】:

  • 而不是“if indexPath.row == 5”,您是否尝试过“if indexPath.row > 5”??
  • 它不起作用,它只模糊 1 行,当我向下滚动时,模糊出现在最后一行。
  • 哦,我明白了,但也许你可以给我们一些截图,或者更好的 GIF
  • 已添加屏幕截图。
  • 太棒了。在答案部分查看我的答案:)

标签: ios swift uitableview cell blur


【解决方案1】:

您不能共享在单元格之间移动的单个视觉效果视图。 (一个视图只能在 w 视图层次结构中存在一次。如果将其作为子视图添加到 2 个位置,它会从第一个位置删除)。

您的代码也应该使用if indexPath.row >= 5,而不是if indexPath.row == 5

我建议创建 UICollectionViewCell 的自定义子类,该子类具有公共 blurView IBOutlet。在您的 XIB/故事板中的单元格中安装模糊视图。在您的 tableView(_:cellForRowAt:) 方法中,如果行小于 5,则隐藏模糊视图,否则取消隐藏。

【讨论】:

  • 很有意义,我能够完成我想要的。谢谢!
【解决方案2】:

发生这种情况的原因有很多。

  1. 您似乎在视图控制器中分配了一个模糊视图实例。这没有任何意义,因为您需要 N 个模糊视图,因为您想为每行添加一个模糊视图 >= 5。
  2. 即使您有多个模糊视图实例,您的逻辑也会专门检查是否有indexPath.row == 5。你会希望它是indexPath.row >= 5

要解决此问题,我建议您采取以下措施:

  1. 将 blurView 属性添加到 CustomTableViewCell。这将确保每个单元格都有自己的模糊视图实例。确保将此模糊视图添加为内容视图的最顶层子视图并覆盖整个内容视图。确保默认情况下隐藏此子视图。
  2. CustomTableViewCell 中,覆盖prepareForReuse 并设置blurView.isHidden = true
  3. 在您的tableView(_:cellForRowAt:) 方法中,设置cell.blurView.isHidden = indexPath.row >= 5

【讨论】:

    【解决方案3】:

    因为您试图将单个 visualEffectView 变量添加到多个单元格。尝试像这样修复您的 cellForRowAt 方法:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
        cell.cellLbl?.text = array[indexPath.row]
        
        if indexPath.row >= 5 {
          let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
          visualEffectView.frame = cell.bounds
          visualEffectView.layer.masksToBounds = true
          cell.addSubview(visualEffectView)
        }
        return cell
      }  
    

    【讨论】:

    • 谢谢,这确实隐藏了剩余的行,但是当我向下滚动然后备份时,模糊覆盖了所有内容。
    • 嗯,这很奇怪,我什至在发布之前尝试了我的代码,它可以工作:((
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多