繁体   English   中英

IOS UITableView 显示数组的前5行

[英]IOS UITableView display first 5 rows of an array

我有一个带有 1 个单元格的 UITableView,当加载数组时,我只想让用户看到前 5 行的内容并模糊 rest。 因此,如果有一个包含 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
    } 

在此处输入图像描述

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

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

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

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

  1. 您似乎在视图 controller 中分配了一个模糊视图实例。 这没有意义,因为您需要 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

因为您正在尝试将单个 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
  }  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM