简体   繁体   中英

Custom table cell not resizing to fit content view

I'm implementing a table view with 3 types of custom cells. As shown below, in the company information section, the headquarters label for my custom table view cell CompanyInfoTableViewCell is getting cut off because I think the custom table cell is not resizing to fit the content view.

在此处输入图片说明

I tried implementing this below code in the viewDidLoad method of the controller containing the table view. This code was suppose to make the cells automatically resize to fit the content, but it didn't work ( Edit: It didn't work because I'm making the custom cells and table view PROGRAMMATICALLY USING NO STORYBOARD ). How do I get my custom table view cell to show all my content?

tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.setNeedsLayout()
self.tableView.layoutIfNeeded()

CompanyInfoTableViewCell Code:

class CompanyInfoTableViewCell: UITableViewCell {
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {        
        //Create industry label
        industryLabel = UILabel(frame: CGRect(x: horOffset, y: 0, width: 0.8*screenSize.width, height: 21))
        industryLabel.center.y = 15
        contentView.addSubview(industryLabel)

        
         //Create headquarters label
        hqLabel = UILabel(frame: CGRect(x: horOffset, y: 0, width: 0.8*screenSize.width, height: 21))
        hqLabel.center.y = 40
        contentView.addSubview(hqLabel)
                
    }
}    

If you are not using the storyboard and AutoLayout constraints then you need to manually calculate the height which the UILabels are going to take based on the content it holds. I don't see any code which calculates the height based on content and accordingly setting the height of your labels and also the height of your custom cell.

You must implement heightForRowAtIndexPath to set the height for your cells.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM