I have a custom cell, which is subclass of UITableViewCell
, call it Cell
.
I have added a UITableViewCell
through a storyboard to a tableview ( tableview's content is set to Dynamic Prototypes) and have set cells class to Cell
. Also I have set the reuse identifier appropriately.
The cell is defined in xib
, and I load it like this:
self.tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "CellIdentifier")
The cell itself has only two elements, and those are, one container view (a UIView
) and one image view (a UIImageView
).
Both of those elements are connected through outlets to the Cell
.
These two elements are positioned in a xib
using the Autolayout
constraints. Also, before the cell is about to display, I do something like this in my ViewController
(tried both cellForRowAtPath
and willDisplayCellForRowAtPath
methods):
cell.imageView.layer.cornerRadius = cell.imageView.layer.frame.height / 2.0
cell.imageView.layer.masksToBounds = true
cell.containerView.layer.cornerRadius = cell.containerView.layer.frame.height / 2.0
cell.containerView.layer.borderColor = UIColor.lightGray.cgColor
cell.containerView.layer.borderWidth = 1
and in both cases, at the time when I call UITableView's insertRows(atIndexPaths)
method, the cell is inserted, but it is not displayed properly. The next time, i insert new row (cell), the previous one is drawn correctly...And so on...
Here is how I insert cells (on a button click event):
func addCell(_ title: String) {
titles.append(title)
let indexPath = IndexPath(row: messages.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .bottom)
tableView.endUpdates()
tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
So, how to have a cell drawn correctly in this case?
cell.imageView.layer.cornerRadius = imageView.layer....
is worrying. To what is the right hand sideimageView
referring? In answer to your question for fixed height cellscellForRowAt
is a fine place to do this, but I wonder whatcell.imageView.layer.frame.height
value is. Even better, the very best place for adjusting rounding is in thelayoutSubviews
of your cell's subclass. – Rob Sep 30 '17 at 17:25layoutSubviews()
method of my cell. – Whirlwind Sep 30 '17 at 18:18imageView
is referring tocell.imageView
. It was a typo. Also, my cells don’t have fixed height... – Whirlwind Sep 30 '17 at 18:41layoutSubviews
, the image view's height is something like zero or whatever size was originally set in the NIB. So you might want to reference the size of thecell
. (Or, you can subclassUIImageView
and have itslayoutSubviews
do the rounding, which might be more hassle than its worth.) When you look at theframe
of the image view inlayoutSubviews
, you'll see precisely what I'm talking about. – Rob Sep 30 '17 at 18:50