Elias Datler Elias Datler - 28 days ago 11
iOS Question

Delete Rows of custom UITableViewCell frame issue

I am relatively new to Xcode and Swift programming, and in my first app, which consists of a tableview with a custom TableViewCell which overrides the variable frame to not cover the full width of the view:

override var frame: CGRect {
get {
return super.frame
}

set {
var frame = newValue
frame.origin.x += 175
frame.size.width -= 350
super.frame = frame
}
}


Everything works as expected, but when I delete a Tableview Cell with
self.tableView.deleteRows(at: [path], with: .automatic)
, a strange issue with the cell appears; it looks like the cell again gets a new (smaller) frame than the old one, but only the visible cells; if the cells get reloaded, the issue is gone. So it just happens right after the delete; if the cell leaves the screen and is then presented again, it goes back to its normal size.
My guess is that `newValueis already a custom frame and then gets customized again which makes it even smaller; but I have no idea how to adress this issue!

Here are screenshots from the iPad version:

Normal tableview

After deleting

Any help will be appreciated! If you need further information, please let me know in the comments! Thank you!

Answer

I would suggest you not to interfere in cell's frame the way you do.

  1. Set cell's backgroundColor to UIColor.clear
  2. Create a custom view on cells's contentView, horizontally centered and 350 points narrower then the cell itself.

Or

  1. Make the whole tableView's width 350 points less then screen width
  2. Forget about changing cells's width

For the first suggestion view hierarchy and autolayout constraints will look similar to this:

enter image description here

The problem is with a custom view I will run into even more troubles because the height of each cell is different from one another

That's another topic altogether. You should use dynamic cell height, described in detail in this RayWenderlich tutorial

Basically, you need to set autolayout constraints properly and do this in viewDidLoad:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

Discouraged approach:

My guess is that `newValueis already a custom frame and then gets customized again which makes it even smaller; but I have no idea how to adress this issue!

If you still want to use your approach, don't just decrement the value, calculate it from scratch using UIScreen's or tableView's width

Instead of this

frame.origin.x += 175
frame.size.width -= 350

Do this:

frame.origin.x = 175
frame.size.width = UIScreen.main.bounds.size.width - 350
Comments