简体   繁体   中英

Self-Sizing TableView Cells based on two subview's height

TableView Description
tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 60.0

Cell Description
I have a cell with 2 Labels(Title, Description) inside a ContainerView and 1 ImageView as below. Cell height will vary based on Description Label's content.
Contraints of all views

There are two cases that I should handle

  1. ContainerView.height greater than (ImageView.height + ImageView.Top + ImageView.Bottom). Here cell's height will be based on ContainerView.height
  2. ContainerView height less than (ImageView.height + ImageView.Top + ImageView.Bottom). Here I expect Cell should consider (ImageView.height + ImageView.Top + ImageView.Bottom) as the height and make ContainerView vertically centre to Cell.
    Expected Result in both the cases

Problem
If I set constraints for 1st case then 2nd case is not working and vice versa (I'm aware that by removing ContrainerView.Top, Bottom and making it Vertically Centre to SuperView case 2 result can be achieved)

Is there a way to achieve expected result in both the cases by using same set of IB constraints and UITableViewAutomaticDimension?

Give fixed height and width to the image view . Otherwise let the tableViewCell know the top and bottom of the imageview. So that it can calculate the correct cell height

Use these delegates,

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
     return 100; // height of default cell
 }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

Edit

Try this one.

Your view hierarchy should be like this

在此处输入图片说明

ImageView Constraints

在此处输入图片说明

Add a view and put both labels into it.

Label Container contraints

在此处输入图片说明

Label Title constraint

在此处输入图片说明

Label Description constraint

在此处输入图片说明

Edit Output

在此处输入图片说明

First make sure that you are using self-sizing cells: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithSelf-SizingTableViewCells.html

Make Top and Bottom constraints for both image view and the container view to the edges of the cell and make them >= .

Alternatively, you could try Horizontal Stack View and make rigid (highest priorities) constraints to each edge of the cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM