0

Hi. I’m already tried to find some info about it at Goodle, but nothing could help me.
I’m swift beginner. Help me, please.

I want to auto layout this TableViewCell in TableViewController.

TableViewController

Now it’s look fine in IB, Preview and Simulator, but only on this screen size, sure.

Then I added by 5 constrains, as I saw at one StackOverflow answer, to each of subview of Cell like this:

enter image description here

and now, when I run project is look crashed:

enter image description here

WHY ?

igolka97
  • 288
  • 2
  • 11

2 Answers2

2

You can use UIStackView for such kind of nested views. It just reduces the number of constraints required to be applied by the developer.

Example:

1. UITableViewDataSource

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return 2
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    return tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
}

2. Storyboard: View Hierarchy and Constraints:

enter image description here

3. Output:

enter image description here

I haven't used the height/estimatedHeight UITableViewDelegate methods. It will be automatically calculated by the cell (if the constraints are right and the cell is able to calculate its own height).

PGDev
  • 23,751
  • 6
  • 34
  • 88
-1

If you added these 5 constraints to each subview of your cell, then it's incorrect. Moreover, contentView is also a subview of the cell and you're modifying its width - thus showing a reduced width. Plus, each of the subviews (that shouldn't include the contentView) should have different constraints.

You can also let Xcode determine estimate the height of the cell automatically based on your constraints using UITableViewAutomaticDimension.

Kunal Shah
  • 1,071
  • 9
  • 24