简体   繁体   中英

Custom UITableViewCell with auto layout issue

I have a custom UITableViewCell as seen below:

在此处输入图片说明

My image has a fixed width and height, my description label fills the remaining width and has an automatic height based on its content.

This creates a problem because, depending on the description label's height, there's never a fixed anchor to attach the bottom of my cell to.

So, currently I have a constraint from the bottom of the image to the bottom of the cell's margin, with a relation of >= 0. Similarly, I have a constraint on the bottom of the description label with a relation of >= 0.

However, when I run my app auto layout always uses the image constraint to calculate the bottom instead of the description label constraint, even when when the description label is taller. This clips my label.

I have a feeling this might be something to do with content hugging and compression resistance but both views are 251 and 750 respectively. (I've toyed around with these but no luck - I don't fully understand them)

How do I successfully use auto layout to attach the bottom of the cell to the image when the description is smaller than the image? And vice versa?

You can remove the bottom constrain from the label and set the vertical content hugging and vertical content compression to 1000 (required). This basically tells the label it can have unlimited vertical height as long as it hugs the content. Problem is if the description is very long it will go pass the cell bottom causing the text to get cut midline. To avoid that headache, set the the label's max line number and the line break mode to "truncate tail".

This all assume you don't mind description text getting cut. If you want the cell's height to dynamically change according to its content that's a different story.

For dynamic cell height, change the bottom constrain of the image and description label to == then add these two methods to your viewController:

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  100; // min cell height
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

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