简体   繁体   中英

IOS Swift 5 Add Custom TableViewCell Separator for Dynamic Height TableView Cell

I am creating a dynamic height TableViewCell based on the contents of the Cell. I would like to create a custom separator between the cells. I have the following code in the TableViewCell swift file. It appears that the custom separator is created using the default height of the cell and not the calculated height of the cell based on the contents of the cell - which was calculated in the TableView heightForRowAt override function. As a result, the customer separator is rendered across the cell. It appears that the awakeFromNib is called before the height calculation. Any suggestions?

class FeedTableViewCell: UITableViewCell { 

    override func awakeFromNib() {
        super.awakeFromNib()

        // add a custom seperator between table view cells.
        let screenSize = UIScreen.main.bounds
        let separatorHeight = CGFloat(10.0)
        let additionalSeparator = UIView.init(frame: CGRect(x: 0, y: self.frame.size.height-separatorHeight, width: screenSize.width, height: separatorHeight))
        additionalSeparator.backgroundColor = UIColor(named: "TEXTVIEWCELL_SEPARATOR")
        self.addSubview(additionalSeparator)
    }
}

The awakeFromNib is called before the height calculation. While the solution works for fixed height TableViewCells, it won't work for variable height TableViewCells. The solution that I used was to create a view on the bottom of the TableViewCell, use constraints to pin it to the bottom of the TableViewCell. You can size the view to 10pt and of course set the color. I did this in StoryBoards, not programmatically.

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