swiftuitableviewswift3tableviewheightforrowatindexpath

Setting heightForRowAt indexPath for multiple rows to 0


I have an array of integers and I am trying to set the UITableViewCell height to 50 for all rows within the array, and the remaining rows to 0. Using Swift 3, my array returns [0,1,3,6] and I am looping through all elements within the array using a for loop.

In my heightForRowAt indexPath function, I am comparing the indexPath.row to these values and setting the height appropriately. However, it will only work for the first element, and not all.

Simply put in code:

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
    }

What logic am I missing so that the height is set appropriately for all elements within array and not just the first? I have tried other approaches using indexPath.contains, but to no avail.


Solution

  • Don't loop. Just check the current indexPath.

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