Swift - tableView Row height updates only after scrolling or toggle expand/collapse

喜欢而已 提交于 2019-11-27 15:47:33

You can try this for String extension to calculate bounding rect

extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return boundingBox.height
    }
}

Source: Figure out size of UILabel based on String in Swift

Here's what I got working based on my understanding of the overall goals of OP. If I'm misunderstanding, the following is still a working example. Full working project is also linked below.

Goals:

  • Dynamically sized TableViewCells that are also
  • Collapsable to show/hide additional details

I tried a number of different ways, this is the only one that I could get working.

Overview

Design makes use of the following:

  • custom TableViewCells
  • Autolayout
  • TableView Automatic Dimension

So if you're not familiar with those (especially Autolayout, might want to review that first.

Dynamic TableViewCells

Interface Builder

Lay out your a prototype cell. It's easiest to increase the row height size. Start simply with just a few elements to make sure you can get it working. (even though adding into Autolayout can be a pain). For example, simply stack two labels vertically, full width of the layout. Make the top label 1 line for the "title" and the second 0 lines for the "details"

Important: To configure Labels and Text Areas to grow to the size of their content, you must set Labels to have 0 lines and Text Areas to not be scrollable. Those are the triggers for fit to contents.

The most important thing is making sure there is a constraint for all four sides of every element. This is essential to get the Automatic Dimensioning working.

CollapsableCell

Next we make a very basic custom class for that table cell prototype. Connect the labels to outlets in the custom cell class. Ex:

class CollapsableCell: UITableViewCell {

  @IBOutlet weak var titleLabel: UILabel!
  @IBOutlet weak var detailLabel: UILabel!

}

Starting simply with two labels is easiest.

Also make sure that in Interface Builder you set the prototype cell class to CollapsableCell and you give it a reuse ID.

CollapsableCellViewController

On to the ViewController. First the standard things for custom TableViewCells:

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return data.count
  }


  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "collapsableCell", for: indexPath) as! CollapsableCell
    let item = data[indexPath.row]

    cell.titleLabel?.text = item.title
    cell.detailLabel?.text = item.detail

    return cell
  }

We've added functions to return the number of rows and to return a cell for a given Row using our custom Cell. Hopefully all straightforward.

Now normally there would be one more function, TableView(heightForRowAt:), that would be required, but don't add that (or take it out if you have it). This is where Auto Dimension comes in. Add the following to viewDidLoad:

  override func viewDidLoad() {
    ...
    // settings for dynamic resizing table cells
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 50
    ...
  }

At this point if you set up the detail label to be 0 lines as described above and run the project, you should get cells of different sizes based on the amount of text you're putting in that label. That Dynamic TableViewCells done.

Collapsable Cells

To add collapse/expand functionality, we can just build off the dynamic sizing we have working at this point. Add the following function to the ViewController:

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    guard let cell = tableView.cellForRow(at: indexPath) as? CollapsableCell else { return }
    let item = data[indexPath.row]

    // update fields
    cell.detailLabel.text = self.isExpanded[indexPath.row] ? item.detail1 : ""

    // update table
    tableView.beginUpdates()
    tableView.endUpdates()

    // toggle hidden status
    isExpanded[indexPath.row] = !isExpanded[indexPath.row]

  }

Also add 'var isExpanded = Bool' to your ViewController to store the current expanded status for your rows (This could also be class variable in your custom TableViewCell).

Build and click on one of the rows, it should shrink down to only show the title label. And that's the basics.

Sample Project: A working sample project with a few more fields and a disclosure chevron image is available at github. This also includes a separate view with a demo of a Stackview dynamically resizing based on content.

A Few Notes:

  • This is all done in normal TableViewCells. I know the OP was using header cells, and while I can't think of a reason why that wouldn't work the same way, there's no need to do it that way.
  • Adding and removing a subView is the method I originally thought would work best and be most efficient since a view could be loaded from a nib, and even stored ready to be re-added. For some reason I couldn't get this to resize after the subViews were added. I can't think of a reason it wouldn't work, but here is a solution that does.

If I understood your question correctly, what you want to do is to resize your tableHeaderView when you call toggleSection.

Therefore what you need to do for your tableHeaderView to resize is this

// get the headerView
let headerView = self.tableView(self.tableView, viewForHeaderInSection: someSection)

// tell the view that it needs to refresh its layout
headerView?.setNeedsDisplay()

// reload the tableView
tableView.reloadData() 
/* or */ 
// beginUpdates, endUpdates

Basically what you would do is to place the above code snippet inside your function toggleSection(header: CollapsibleTableViewHeader, section: Int)

func toggleSection(header: CollapsibleTableViewHeader, section: Int) {
    ...

    // I'm not sure if this `header` variable is the headerView so I'll just add my code snippet at the bottom
    header.setNeedsDisplay() 


    /* code snippet start */
    // get the headerView
    let headerView = self.tableView(self.tableView, viewForHeaderInSection: someSection)

    // tell the view that it needs to refresh its layout
    headerView?.setNeedsDisplay()
    /* code snippet end */

    // reload the tableView
    // Adjust the height of the rows inside the section
    tableView.beginUpdates()


    // You do not need this
    for i in 0 ..< sections.count {
        tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: i, inSection: section)], withRowAnimation: .Automatic) 
    }
    // You do not need this


    tableView.endUpdates()
}

Explanation: A tableView's headerView/footerView does not update its layout even if you call reloadData() and beginUpdates,endUpdates. You need to tell the view that it needs to update first and then you refresh the tableView

Finally you also need to apply these two codes

func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
    return estimatedHeight
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableViewAutomaticDimension
}

In this method,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + heightOfLabel2!)
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

instead of using heightOfLabel2, try implementing the following method to calculate heights specific to each cell(since we know the text to be filled, its font and label width, we can calculate the height of label),

func getHeightForBenefitDetailText2ForIndexPath(indexPath: NSIndexPath)->CGFloat

So your method should look like this,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + getHeightForBenefitDetailText2ForIndexPath(indexPath))
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

And regarding your problem to expand few cells by for the very first time, make sure you set the collapsed property to true for those cells before reloading the table.

As a performance improvement, you can store the height value calculated for each expanded cell in a dictionary and return the value from the dictionary, to avoid the same calculation again and again.

Hope this helps you. If not, do share a sample project for more insight about your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!