iOS TableView Constraints doesn’t work [duplicate]

大城市里の小女人 提交于 2020-01-06 05:51:13

问题


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.

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:

and now, when I run project is look crashed:

WHY ?


回答1:


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:

3. Output:

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).




回答2:


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.



来源:https://stackoverflow.com/questions/47012524/ios-tableview-constraints-doesn-t-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!