iOS Swift adjust Table View cells height to fit contents

iOS Swift self sizing Table view cells example
If you create the UITableViewCell with auto layout constraints then UITableView automatically takes care of the calculating the row height,
by default rowHeight value is UITableView.automaticDimension

myTableView.translatesAutoresizingMaskIntoConstraints = false
myTableView.estimatedRowHeight = 44 
myTableView.rowHeight = UITableView.automaticDimension
iOS Swift self sizing Table view cells example

Source for UIViewController


import UIKit

class ViewController1: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    //my sample data for table view
    private let myArray: NSArray = [
        "Row# 1",
        "Row# 2",
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "Row# 4",
        "Row# 5"]
    private var myTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "Main View"
        
        myTableView = UITableView()
        myTableView.register(CustomCell.self, forCellReuseIdentifier: "MyCell")
        myTableView.dataSource = self
        myTableView.delegate = self
        
        //autolayout and Table row height config
        myTableView.translatesAutoresizingMaskIntoConstraints = false
        myTableView.estimatedRowHeight = 44
        myTableView.rowHeight = UITableView.automaticDimension
        
        self.view.addSubview(myTableView)
        
        //auto layout for the table view
        let views = ["view": view!, "tableView" : myTableView]
        var allConstraints: [NSLayoutConstraint] = []
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "V:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "H:|[tableView]|", options: [], metrics: nil, views: views as [String : Any])
        NSLayoutConstraint.activate(allConstraints)
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath)
        -> CGFloat {
        switch indexPath.row {
            
        //changing the Row# 2 to fixed height, usually there is no need for this
        case 1:
            return 60
        //default to automatic height calculation
        default:
            return UITableView.automaticDimension
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Num: \(indexPath.row)")
        print("Value: \(myArray[indexPath.row])")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
        -> Int {
        return myArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
       
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell",
                        for: indexPath as IndexPath) as! CustomCell
        cell.myLabel.text = "\(myArray[indexPath.row])"
        return cell
    }

}



Source for custom UITableViewCell


import UIKit

class CustomCell: UITableViewCell {

    let myLabel = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        myLabel.numberOfLines = 0
        myLabel.lineBreakMode = .byWordWrapping
        myLabel.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(myLabel)
        
        let views = [
            "contentView" : contentView,
            "label" : myLabel
            ]
        
        var allConstraints: [NSLayoutConstraint] = []
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "V:|-[label]-|", options: [], metrics: nil, views: views)
        allConstraints += NSLayoutConstraint.constraints(withVisualFormat:
            "H:|-[label]-|", options: [], metrics: nil, views: views)
        NSLayoutConstraint.activate(allConstraints)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.