skip to Main Content

I just dropped a view inside my table view, the view is containing images and labels. But Label content is dynamic and don’t wanna crop it instead I want to increase the height of the view as per need. But header view also doesn’t accept constraints. So would I achieve? The problem is occurring for the label which is placed above the find friends button.
enter image description here

2

Answers


  1. you need to estimate label height with text and plus with image/ button height to calculate total height of header view

    func estimatedLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
    
        let size = CGSize(width: width, height: 1000)
    
        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
    
        let attributes = [NSAttributedStringKey.font: font]
    
        let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height
    
        return rectangleHeight
    }
    

    here is the method to estimate header height:

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return label size + other size
    }
    

    or you can use auto layout to avoid estimate height:

    • set label numberOfLines = 0
    • set vertical padding constraint between each cell in vertical direction
    • return UITableView.automaticDimension in
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
       return UITableView.automaticDimension
    }
    
    Login or Signup to reply.
  2. TableView header height is not automatically refreshed and you must recalculate the height by your own each time its content changes. Heigh recalculation and tableview header refresh can be done in ‘viewDidLayoutSubviews’ method.

    override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
    
            guard let headerView = tableView.tableHeaderView else {
                return
            }
            let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    
            if headerView.frame.size.height != size.height {
                headerView.frame.size.height = size.height
                tableView.tableHeaderView = headerView
                // This only seems to be necessary on iOS 9.
                tableView.layoutIfNeeded()
            }
        }
    

    The answer and code snipet are brief summary of "Variable Height Table View Header" post, accessible at usyourloaf

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search