【问题标题】:Setting heightForRowAt indexPath for multiple rows to 0将多行的 heightForRowAt indexPath 设置为 0
【发布时间】:2018-06-08 06:01:30
【问题描述】:

我有一个整数数组,我试图将数组中所有行的 UITableViewCell 高度设置为 50,其余行设置为 0。 使用 Swift 3,我的数组返回 [0,1,3,6],我正在使用 for 循环遍历数组中的所有元素。

在我的heightForRowAt indexPath 函数中,我将indexPath.row 与这些值进行比较并适当地设置高度。但是,它只适用于第一个元素,而不是全部。

只需输入代码:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isSearching == true{
        searchBarIndexs.sorted(by: {$0 < $1})
        for allvalues in searchBarIndexs{
            if indexPath.row == allvalues{
                return 52
            } else {
                return 0
            }
        }
    } else {
        return 52
    }
    return 52
}

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if isSearching{
            return searchBarIndexs.count
        } else {
            return usernames.count
        }

    }




override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! usersProfileTableViewCell
            cell.userUsernameLabel.text = usernames[indexPath.row]
            cell.userIdLabel.text = userIDs[indexPath.row]

            self.allimages[indexPath.row].getDataInBackground { (data,error) in
                if let imageData = data {
                    if let downloadedImage = UIImage(data: imageData){
                        cell.profileImage.image = downloadedImage

                    }
                }
            }

        return cell
    }

我缺少什么逻辑,以便为数组中的所有元素设置适当的高度,而不仅仅是第一个?我尝试过使用 indexPath.contains 的其他方法,但无济于事。

【问题讨论】:

  • edit您的问题并显示您完整的heightForRowAt方法(作为文本)。
  • 嗨 rmaddy,很抱歉,我已经正确缩进并包含了完整的 heightForRowAt 方法

标签: swift uitableview swift3 tableview heightforrowatindexpath


【解决方案1】:

不要循环。只需检查当前的indexPath

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if isSearching {
        return searchBarIndexs.contains(indexPath.row) ? 52 : 0
    } else {
        return 52
    }
}

【讨论】:

  • 嗨@rmmaddy 感谢您的帮助和及时回复。我仍在尝试合并此修复程序,因为我对内联语句没有太多实践。基本上,我使用搜索栏过滤表格视图中的数据,但使用这种方法它只返回特定的搜索,因此试图查看缺少的内容。
  • 这是您声称想要的代码。这里的逻辑是,如果您正在搜索,则仅为在 searchBarIndexs 数组中找到的行返回 52 的高度。如果这不起作用,那么要么您的要求不正确,要么您的 searchBarIndexs 人口不正确。
  • 根据我的搜索栏显示我的 searchBarIndexs 数组是正确的:在我的用户表上,当我在搜索栏中输入“M”并打印 searchBarIndexs 数组时,我返回 [0, 1 , 3, 6] 但表格视图显示 3 个结果。在搜索栏中,当我输入“S”时,我的 searchBarIndexs 数组返回 [2, 5],而 tableview 中没有显示任何内容
  • return searchBarIndexs.count 在您的numberOfRowsInSection 中必须是return usernames.count
  • 傻了我.. 非常感谢您一直以来的帮助和及时的回复。非常感谢您的帮助,感激不尽!
猜你喜欢
  • 2018-07-16
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 2020-10-08
  • 2011-04-13
  • 1970-01-01
相关资源
最近更新 更多