1

I'm new to swift and working on a project in Swift 3.0 where I have a UITableView with three custom cells. In the first one I just have a image,button and a label. In the second one I have an image plus a label along with expandable and collapsible headers.Thus I have three different sections for this second cell. And lastly the third one is also contains just a label. In the first cell the UILabel is set underneath the image which contains a description about a person (constraints are been set). My requirement is only for the first cell dynamically adjust the cell size based on the size of the description. Help would much appreciate, the code as bellow.

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    print("Number of Sections: \(section)")
    return arrayForTableView[section]
}

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let headerView : UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    headerView.contentView.backgroundColor = UIColor.yellow.withAlphaComponent(1.0)
}

func tapped(sender: UITapGestureRecognizer)
{
    if let tag = sender.view?.tag{
        expanedSections[tag] = !expanedSections[tag]
    }
    tableView.reloadData()
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerView = UITableViewHeaderFooterView()
    headerView.tag = section

    let tapRecog = UITapGestureRecognizer(target: self, action: #selector(tapped))

    tapRecog.numberOfTapsRequired = 1
    tapRecog.numberOfTouchesRequired = 1
    tapRecog.delegate = self
    headerView.addGestureRecognizer(tapRecog)
    return headerView
}

func numberOfSections(in tableView: UITableView) -> Int {
    return arrayForTableView.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0:
        return 1
    case 1:
        return expanedSections[section] ? getItemsForSection(self.tableData.freeGifts): 0
    case 2:
        return expanedSections[section] ? getItemsForSection(self.tableData.exclusiveOffers) : 0
    case 3:
        return expanedSections[section] ? getItemsForSection(self.tableData.allAudios) : 0
    case 4:
        return expanedSections[section] ? getItemsForSection(self.tableData.testamonials) : 0
    default:
        return  0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // var cell: UITableViewCell?

    print("Section : \(indexPath.section) : \(indexPath.row)")

    switch indexPath.section {
    case 0:
      let cell =  tableView.dequeueReusableCell(withIdentifier: "HealerDetailsCell", for: indexPath) as! HealerDetailsTableViewCell

      //cell.aboutLabel.preferredMaxLayoutWidth = (tableView.bounds)
          cell.aboutLabel.sizeToFit()
        populateHealerDetails.populateTable(cell, self.tableData.healerDetails)
        return cell
    case 1:

        if tableData.freeGifts.count > 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
        PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.freeGifts[indexPath.row] as! NSDictionary)
            return cell
        } else {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        cell.textLabel?.text = "No Free Gifts At This Time"
            return cell
        }
    case 2:

        if tableData.exclusiveOffers.count > 0 {
         let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
        PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.exclusiveOffers[indexPath.row] as! NSDictionary)
            return cell
        }else {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
         cell.textLabel?.text = "No Exclusive Offers At This Time"
            return cell
        }
    case 3:

        if tableData.allAudios.count > 0{
        let cell = tableView.dequeueReusableCell(withIdentifier: "OffersCell",for: indexPath)
        PopulateHealerDetailsAndOffers.populateTable(cell, self.tableData.allAudios[indexPath.row] as! NSDictionary)
            return cell
        }else{
            let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
            cell.textLabel?.text = "NO Audios To Display"
            return cell
        }
    case 4:

       if tableData.testamonials.count > 0 {
          let  cell = tableView.dequeueReusableCell(withIdentifier: "TestamonialsCell", for: indexPath)
          return cell
       }else{
        let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
        cell.textLabel?.text = "No Testamonials"
        return cell
        }
    default:
         let  cell = tableView.dequeueReusableCell(withIdentifier: "TestamonialsCell", for: indexPath)
          return cell
    }

}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //let indexPath = tableView.indexPathForSelectedRow!
    //let currentCellValue = tableView.cellForRow(at: indexPath)! as UITableViewCell
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
danu
  • 1,079
  • 5
  • 16
  • 48

4 Answers4

1

1.Set the constraint of label.

2.Put numberOflines is equal to 0(Through storyboard or programmatically)

  1. Add this code in viewDidLoad:

    tableView.estimatedRowHeight = 300
    tableView.rowHeight = UITableViewAutomaticDimension
    
Shabbir Ahmad
  • 615
  • 7
  • 17
0

Use this delegate method

   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
AkBombe
  • 638
  • 4
  • 10
  • already tied this but not helping since I have three custom cells – danu Apr 26 '17 at 11:45
  • Add this lines in viewDidLoad method 1. self.tableView.rowHeight = UITableViewAutomaticDimension 2. self.tableView.estimatedRowHeight = 44.0 – AkBombe Apr 26 '17 at 12:18
  • Also check your constraints if you are using label make number of lines to zero and don't give height constraint to label just hold label from top, bottom, left and right. – AkBombe Apr 26 '17 at 12:19
0

I think you want to expand/elapse UITableViewCell depending on the data each cell would have at runtime. I suppose, you already have implemented all of the first aid options regarding UITableView in swift.

Please try this method, which will always be called when your each cell is loaded.

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    //CellAnimator.animateCell(cell: cell, withTransform: CellAnimator.TransformWave, andDuration: 1)
   //This commented line possibly might not be your requirement.
  //But this is actually used to animate cell while loading.
  //You can try some constraints or cell height related stuff here which would definitely work for each cell differently.


  //Try calling cell specific loads either.
  tableView.scrollToRow(at: indexPath as IndexPath, at: .none, animated: true)

        /*let indexPath = IndexPath(item: (selectedCellIndexPath?.row)!, section: 0)
        tableView.reloadRows(at: [indexPath], with: .none)
        checkTrue = true
        */


}

Please check out this:

   import UIKit

   class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!
var tableViewDataSource = ["fewhf wfh wf wfw h dfw \n\n wufhw f ewfw  wf w \n\n  f wefe wfef w","fewhf wfh wf wfw h dfw \n\n wufhw f ewfw  wf w \n\n  f wefe wfef w",
"fewhf wfh wf wfw h dfw \n\n wufhw f ewfw  wf w \n\n  f wefe wfef w",
"fewhf wfh wf wfw h dfw \n\n wufhw f ewfw  wf w \n\n  f wefe wfef w"
]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    tableView.delegate = self
    tableView.dataSource = self
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


//Tableview 
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return tableViewDataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "CellHere") as! TableViewCellHere

    cell.cellHere.text = tableViewDataSource[indexPath.row]
    cell.cellHere.textAlignment = .justified
    return cell
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {


    if indexPath.row == 0 || indexPath.row == 1
    {
        return 120.0
    }
    else
    {
        return 50.0
    }


}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 || indexPath.row == 1
    {
        return 120.0
    }
    else
    {
        return 50.0
    }

  }

    }

This is working for me like this: enter image description hereenter image description hereenter image description here

Asim Khan
  • 508
  • 1
  • 7
  • 21
  • yes actually all my code works fine, just the content is only partially visible. I tried the above code too but still no difference. – danu Apr 26 '17 at 11:00
  • sir if u read my code ul se that there is only one row for the section 0, which is my first cell. Forget the expandable and collapsable concept, in that cell I have a UILable set underneath an image which displays a paragraph. For now I only see few lines. I want this cell to adjust based on the content size – danu Apr 26 '17 at 11:14
0

For version >= iOS 8

override func viewDidLoad()
{
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0; // set to whatever your "average" cell height is
}

Steps to set constraints on storyboard:here

Important

  • If multiple lines labels, don't forget set the numberOfLines to 0.
  • Don't forget label.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds)
Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26