C.M.
C.M.

Reputation: 1561

Swift: UITableViewCell size to width of parent UITableView with autolayout enabled

I'm experimenting with autolayout and am running into trouble with UITableViewCell since they're created at runtime. My cells are loaded from a xib from the main ViewController. This xib has View mode set to Aspect Fill.

I've read about different ways to do this online and have yet to get any of them working. What's considered the best way to handle this?

enter image description here

Upvotes: 2

Views: 4094

Answers (1)

user4151918
user4151918

Reputation:

It looks like your constraints aren't set properly, as the cell is shorter than the image's height.

Using AutoLayout and self-sizing cells is the easiest way to handle what you want to do. Once your constraints are setup properly for your custom cell, tableView:cellForRowAtIndexPath: can call dequeueReusableCellWithIdentifier:forIndexPath: and all the subview layout will be handled for you.

See the detailed walkthrough by smileyborg in his answer to Using Auto Layout in UITableView for dynamic cell layouts & variable row heights.

He also provides workarounds for the minor issue with the initial cell width being based on the storyboard cell, instead of the tableView width. I worked around it by setting the cell's initial width to the tableView's width, as Rasputin had suggested.

Upvotes: 2

Related Questions