user3674647 user3674647 - 3 months ago 33
iOS Question

Swift UITableViewCell Subview Layout Updating Delayed

I have a subclass of UITableViewCell and a subclass of UITableViewController. I'm popualating the tableview with my custom cells.

I created a UITableViewCell in my storyboard, made its class my custom UITableViewCell Swift file, and gave it an identifier. Then I create cells in the controller with:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myIdentifier", forIndexPath: indexPath indexPath)
return cell
}


In my custom cell (on the storyboard) I have a UIImageView with the following constraints:

Image View Constraints

The constant for the top space constraint is 0, which I thought means the ImageView top would be flush with the cell top.

However, the images in my cell are pushed down a bit:

UITableView with custom cell

The white is just the table section header, that's working perfectly. However, you can see the orange gap that appears above the image (that orange is the background color of the cell), and I don't want that there.

I tried setting the image frame in the custom cell's awakeFromNib:

@IBOutlet weak var img: UIImageView!
override func awakeFromNib() {
img.frame = CGRectMake(0, 0, img.frame.width, img.frame.height)
}


But this had no effect, so I tried setting the frame in layoutSubviews:

override func layoutSubviews() {
img.frame = CGRectMake(0, 0, img.frame.width, img.frame.height)
}


This worked, but only after scrolling down and back up on the TableView. The first two cells have the orange gap, but if you scroll to the third one and back up, then the gap is gone.

Does anyone know why this is happening? How can I make the imageview be positioned at (0, 0) right away instead of only after scrolling down and back up?

Answer

When I try to reproduce your situation and drag the imageView to align to the top of the cell the Xcode suggested constraint is -8, and it works fine like that but if i set it to 0 I get the background color like your problem, try setting the top constraint to -8 or whatever Xcode is suggesting.

I'm not very familiar with AutoLayout so I can't clarify why Xcode wants to set it to -8