I have a UIView with a NavigationController and a tableView. The table has 1 prototype cell and contains some labels. All "designed" with the storyboard and all constraints are set automatically. So I did with 10 UIViews (for iPhone) in my app, 9 of them displaying correct in portrait- and landscape-mode. One is ok for Portrait-mode, when turning to landscape there is a space about 300px between the cell witch has content for one line and the cell which has content for 20 or 30 lines. And the same space is at the end of that cell. I tried several other constraints, also manual done. I tried other x/y/width/height - settings for the labels without success. The code for the cell-height is:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (!self.cellNews) {
self.cellNews = [self.tableView dequeueReusableCellWithIdentifier:#"CellNews"];
}
theAktuellList = [app.aktuellArray objectAtIndex:indexPath.row];
NSString *currentLanguage =
[[NSString alloc] initWithContentsOfFile:[NSHomeDirectory() stringByAppendingPathComponent:#"/Documents/sprache.txt"]
encoding:NSUTF8StringEncoding error:NULL];
if ([currentLanguage isEqual:#"de"])
{
self.cellNews.Titel.text = theAktuellList.TitelD;
self.cellNews.Datum.text = theAktuellList.DatumD;
self.cellNews.Nachricht.text = theAktuellList.NachrichtD;
self.cellNews.Wichtig.text = theAktuellList.WichtigD;
}
else
{
if ([currentLanguage isEqual:#"fr"])
{
self.cellNews.Titel.text = theAktuellList.TitelF;
self.cellNews.Datum.text = theAktuellList.DatumF;
self.cellNews.Nachricht.text = theAktuellList.NachrichtF;
self.cellNews.Wichtig.text = theAktuellList.WichtigF;
}
else
{
self.cellNews.Titel.text = theAktuellList.TitelE;
self.cellNews.Datum.text = theAktuellList.DatumE;
self.cellNews.Nachricht.text = theAktuellList.NachrichtE;
self.cellNews.Wichtig.text = theAktuellList.WichtigE;
}
}
[self.cellNews layoutIfNeeded];
CGFloat height = [self.cellNews.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
The app is a universal-app. This UIView with the tableView inside and the same content works without any issues on the Pad. Where is my fault or what can I change or try to solve that problem?
EDIT due to Answer of Raj:
Hi Raj, thanks for the link. I went through and found nothing. But I do it again tomorrow. Maybe I didn't talk about the cell and its labels. I have 1 prototype-cell with a height of 45. Inside I have 4 labels with each 25 hight and 10 top and 10 bottom constraint. "Title" has 20 left & right, "Date" has 30 left and 20 right, "Message" has 30 left and 20 right and "Wichtig" has 20 left and right. They are all placed one over the other, because in each cell only one label is used. That means the first cell contains only the Titel, the second cell the Date, the third cell the Message and so on. All constraints of each label are blue and as long as I have only one line of text in the label the cell is built correct. With every additional text line the "top- and bottom-padding" is growing. But the constraint is set to a fixed value.
EDIT 14.08.2014:
I went through the tutorials without any positiv changes. The labelheight is "calculated depending on the labelwidth in portrait orientation. When rotating to landscape, the label has exact the same height as in portrait orientation but the width has grown to nearly twice. The result is a less real textheight which is centered horizontal in the label.
I added a, I think it is more a dirty trick than a proper solution, a returning of height depending the label with long content is used:
CGFloat height = [self.cellNews.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
if ([self isLandscapeOrientation]) {
if (theAktuellList.NachrichtD == nil) {
return height + 1;
} else {
return height/1.5;
}
} else {
return height + 1;
}
This works "optically" fine, I get no hint or error but there must be better ways of solving that issue. Every help in which direction to learn/think or searching would be nice.
Please go through the below mentioned tutorial which explain Dynamic Table View Cell Height and Auto Layout using which you will get an intended output
http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout
Related
There's more content in my Table View, but this cell is getting cut off and not showing more content:
... So I'm not able to scroll any more, even there is more content.
If I pull up with my finger it shows more content, but then when I let my finger off the cell it goes back to the state show in the image above.
I've tried making sure I set height and width in the Labels and Images in AutoLayout since I thought that might be a problem, but still hasn't fixed it.
Any ideas? Thanks!
UPDATE - Table View structure in Storyboard
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id model = self.model[indexPath.row];
if ([model isKindOfClass:[DBase self]]) {
return 520;
}
else {
return tableView.rowHeight; // return the default height
}
}
I was having this problem as well but mine was only cutting off a single cell. I solved it and thought I'd post this here as it may help others in the future
I was using custom cells created from nibs. Some of my cells could change heights so I was also using this:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 61
I figured out the issue was that I was setting top, left, right and height constraints on my view. I needed to set the bottom constraint as well or else my row height would be way smaller than it should be.
So if you are having this problem check if your row heights aren't smaller than the views that they contain.
I suggest adding height and width constraints to your UITableViewContoller or UITableView in the storyboard.main.
Depending on the size of your device, the UITableView size will remain constant unless you set constraints that will work across all devices.
I'm trying to adjust a UITableViewCell's size to its content. This is basically for a chat view, where I list all previous messages and allow the user to scroll the conversation content.
So I have a UITableView with a few different cell prototypes. Incoming text messages, outgoing text messages, incoming image messages, outgoing image messages, and so on. Inside each cell's content view I have a standard UIView which I intent to use to draw the chat balloon. This view takes almost the cell's inner space (8px offset to the top, left, bottom, and right, all around). Inside that view I want the content. In the case of the text cells (incoming and outgoing) I want a UITextView which will display a text message. This is what I mean:
In yellow is the UIView and inside it the UITextView. Now I want to adjust everything to the text's size. I managed to accomplish the following:
sizeToFit accomplishes exactly what I need for the UITextView
I'm still not sure how to adjust the UIView's size to the UITextView's size.
To adjust the cell's height maybe I could use heightForRowAtIndexPath. I don't need (nor do I think I should) to adjust the cell's width. But a few regards on that: when is this method called? Will the cell already have been instantiated? Will it have already layed out the subviews? Otherwise, how can I tell the content's size?
Any input on this is appreciated!
Edit:
I managed to make a few progresses by following the tutorial posted by #vikingosegundo, but I'm stuck again. This is what I have:
So, basically: the text view has constraints for leading, trailing, distance to top, and distance to bottom. The containing view, on the other hand, has constraints for trailing and distance to top, so that if the size is small then it snaps to the right. I can't had leading constraints or otherwise it will always take the full width of the cell. I'm not sure about distance to bottom constraints.
When a enter a small message it looks great. It's well sized and it snaps to the right.
However, long messages don't span to several lines. Instead it still snaps to the right (OK), but the width grows to the left, indefinitely.
The cell is already adjusting its height to the content's height:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
HyConversationTableViewCell * cell = (HyConversationTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
CGSize size;
[cell setNeedsLayout];
[cell layoutIfNeeded];
size = [cell.textMessageView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 32;
}
I'm guessing that what I need now is something like a text view's maximum width or something, but I realise that's not possible. How do I solve this?
Edit: If I had a leading constraint to the containing view it looks great when the text spans multiple lines, but not when it doesn't. Here's what it looks like:
And:
Edit: As suggested by Alex Zavatone, I changed tableView:heightForRowAtIndexPath: to the following:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
HyConversationTableViewCell * cell = (HyConversationTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
CGSize overflowSize = CGSizeMake(cell.textMessageView.frame.size.width, FLT_MAX);
CGSize sizeAdjusted = [cell.textMessageView sizeThatFits:overflowSize];
return sizeAdjusted.height + 32.0f;
}
It shows a little better as the height is already adjusted, but the behaviour is somewhat erratic. Here's what it looks like at the beginning:
So the height is correct, but the text view does not adjust its width. Also, if I scroll the cells out of screen and then back in (which forces them to redraw) they start behaving erratically in what seems a random criteria. Here's a sample:
Sometimes this happens to the last two cells...
Edit: That last part was fixed by setting Content Hugging Priority and Content Compression Resistance Priority to required and the Intrinsic Size to Placeholder. Now the height shows properly.
If you are using iOS 8 you can use UITableViewAutomaticDimension.
You can check out this example
self.tableView.rowHeight = UITableViewAutomaticDimension;
You can take a look also on this video : What's New in Table and Collection Views in the 2014 WWDC.
Here how, we are doing that
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
AFMediaWithHeadlineCell *cell = [[[NSBundle mainBundle] loadNibNamed:#"AFMediaWithHeadlineCell"
owner:nil
options:nil] firstObject];
[cell loadText:#"Some text"];
return [cell height];
}
actually loadText: loads data into UI, and sizeToFits it.
and height is basic method that calculates cell's height
- (void)loadText:(NSString *)aText
{
self.textView.text = aText;
[self.textView sizeToFit];
}
- (CGFloat)height
{
return self.textView.frame.origin.y + self.textView.frame.size.height + 10; // 10 is margin
}
You can resize the text by setting the height to a large number and then using sizeThatFits on it.
Not sizeToFit.
Like so:
UILabel *label = self.prototypeCell.descriptiveText;
label.numberOfLines = 0;
CGSize sillyLargeHeight = CGSizeMake(label.frame.size.width, 9999);
CGSize labelFrameAdjustedForHeight = [label sizeThatFits:sillyLargeHeight];
return labelFrameAdjustedForHeight.height + 24.0; // 24 is 12 above and 12 below padding.
You can use a label or a textView. If you choose to use a UILabel, you'll need to set the # of lines to 0 so that it will be multiple line.
You can do this within - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
You'll also need to do the same adjustments to set the height on the field (use an IBOutlet) in the willDisplayCell method.
I have a summary cell that has it's height calculated using systemLayoutSizeFittingSize. It mostly works as expected. The height is determined by three multi-line labels (title, author, genre) and an ratings image view, with the outer elements tacked to the contentView.
When the title label overflows into the next line, it sizes appropriately. However when the author label overflows, it doesn't seem to increase the size appropriately.
All the compression resistances on the labels and image view are maxed out at 1000. There is an lower priority constraint on the bottom of the thumbnail to the left, in case the content to the right is smaller than the thumbnail. (#750, bottom == 8 from superview bottom). The ratings image view has a constraint to the bottom of the superview as well (#1000, bottom >= 8 from superview bottom).
Interesting. So I ended up fixing this by always resetting the reference cell frame height before updating the content and calculating the height. Not entirely sure why this step is needed. I have a couple guesses around the autoresize constraints on the contentView taking precedence:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.section) {
case TableSectionSummary: {
TCAnswerDetailAppSummaryCell *cell = self.summaryCell;
CGRect oldFrame = self.summaryCell.frame;
cell.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, mTCTableViewFrameWidth, 400);
[cell configureWithThirdPartyObject:self.app];
[cell updateConstraintsIfNeeded];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + 1;
return height;
}
case TableSectionDetails:
return [TCAnswerDetailBasicCell heightForCellWithTableWidth:mTCTableViewFrameWidth withLabelString:self.app.appDescription withDisclosureArrow:NO];
}
return 0;
}
I have a UITableViewCell that is implemented using storyboard that looks like:
Here is what the cell should look like without an image:
I have been fiddling with the constraints and banging my head trying to figure this out but have had no luck. I have a pretty good understanding of constraints and how to add them programmatically but have had no luck with this specific problem and feel like I am just adding layout constraints to the cell willy-nilly with no logical thought process. The cell represents a newsfeed post which may or may not have an image in the main image view at the top, and should behave as follows. If the cell doesn't have an image in it the bottom bar with the like and comment counts, moves up to align with the top of the cell. I achieved this behaviour by setting a constraint that kept the smaller image view, post title, post time and the post content a set distance away from the bottom of the cell. This approach works and when the cell is resized in the heightForRowAtIndexPath method the subviews move appropriately. The problem comes when the text in the post content is larger then a single line. The height of the cell adjusts correctly but the top of the text view stays at the same location and grows downward and overflows into the next cell. When I place the constraints to align the four subviews with the top of the cell I run into issues when there is no image and the post content is larger then a single line. In this case, the cell resizes to be smaller than its original size and the subviews stay at the distance specified by the constraint. The smaller image, post title, time and content are clipped and don't display. This is such an odd problem with so many different cases. I have been working at this for almost two days and could really use someone else's thoughts on how to solve this issue. I hope this isn't too confusing, thanks for the help!
I have one way to solve this, but I'm sure there are many others. I gave both image views a fixed height constraint. The small image view and the top label (Post Title) have fixed heights to the top of the cell -- both of these as well as the height constraint of the large image view have IBOutlets to them so they can be changed in code. The bottom label (Post Content) has its number of lines set to 0, and has an IBOutlet to its height constraint (all the labels had the standard 21 point height to start). In code, I check for the existence of an image at each indexPath, and change the constraints accordingly.
- (void)viewDidLoad {
UIImage *image1 = [UIImage imageNamed:#"House.tiff"];
[super viewDidLoad];
self.theData = #[#{#"pic":image1, #"post":#"short post"},#{#"post":#"short post"},#{#"pic":image1, #"post":#"Long long post with some extra stuff, and even some more"},#{#"post":#"Long long post with some extra stuff, and even some more"}];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat ivHeight = (self.theData[indexPath.row][#"pic"])? 215 : 0; // 215 is the fixed height of the large image view
CGSize labelSize = [self.theData[indexPath.row][#"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
return 140 + ivHeight + labelSize.height; // the 140 was determined empirically to get the right spacing between the 3 labels and the bottom bar
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.label.text = self.theData[indexPath.row][#"post"];
cell.iv.image = self.theData[indexPath.row][#"pic"];
if(self.theData[indexPath.row][#"pic"] == nil){
cell.heightCon.constant = 0; // heightCon is the outlet to the large image view's height constraint
cell.ivTopCon.constant = 8; // ivTopCon is the outlet to the small image view's spacing to the top of the cell
cell.labelTopCon.constant = 8; // labelTopCon is the outlet to thetop label's spacing to the top of the cell
}else{
cell.heightCon.constant = 215; // this number and the following 2 are taken from the values in IB
cell.ivTopCon.constant = 185;
cell.labelTopCon.constant = 233;
}
CGSize labelSize = [self.theData[indexPath.row][#"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
cell.labelHeightCon.constant = labelSize.height;
return cell;
}
Hey #rdelmar thanks for the solution! Eventually I ended up just designing two different cells in the storyboard file with different reuse identifiers but the same subclass. I then checked in the cellForRowAtIndexPath method if the cell had content or not, and assigned the correct identifier. If this is the incorrect way of doing this, or will cause problems down the road please let me no in the comments.
I have a uilabel setup in a view. It doesn't have a width constraint, but its width is instead determined by a leading constraint to the thumbnail image, and a trailing constraint to the edge of the view.
The label is set to have 0 lines, and to word wrap. My understanding is that this should cause the frame of the uilabel to grow, and indeed it does sometimes. (Previous to auto layout, I would calculate and update the frame of the label in code).
So the result is, it works correctly in some instance and not others. See most cells working correctly there, but the last cell appears to be too big. In fact it's the right size. The title "Fair Oaks Smog Check Test" actually ends with "Only". So my calcuation for the cell size is right, it should be that size. However the label doesn't wrap the text for whatever reason. It's frame width does not extend off to the right, so that's not the issue.
So what is going on here? It's 100% consistent, always on that cell and not the ones above it, which makes me think it's related to the size of the text, and UILabel isn't re-laying out the text once this view is added to the cell (which makes it actually smaller width wise).
Any thoughts?
Some additional information
The height of the cells is calculated from one sample cell I create and store in a static variable:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.items.count == 0) {
return 60;
}
static TCAnswerBuilderCell *cell = nil;
static dispatch_once_t pred;
dispatch_once(&pred,
^{
// get a sample cellonce
cell = [tableView dequeueReusableCellWithIdentifier:TC_ANSWER_BUILDER_CELL];
});
[cell configureCellWithThirdPartyObject:self.items[indexPath.row]];
return [cell heightForCellWithTableWidth:self.tableView.frame.size.width];
}
I configure the cell with my data object on the fly, and then call a method I have on it which calculates the height of the cell with a given table width (can't always rely on the cell frame being correct initially).
This in turn calls a height method on my view, since it is really where the label lives:
- (CGFloat)heightForCellWithTableWidth:(CGFloat)tableWidth {
// subtract 38 from the constraint above
return [self.thirdPartyAnswerView heightForViewWithViewWidth:tableWidth - 38];
}
This method determines the height by figuring out the correct width of the label, and then doing a calculation:
- (CGFloat)heightForViewWithViewWidth:(CGFloat)viewWidth {
CGFloat widthForCalc = viewWidth - self.imageFrameLeadingSpaceConstraint.constant - self.thumbnailFrameWidthConstraint.constant - self.titleLabelLeadingSpaceConstraint.constant;
CGSize size = [self.titleLabel.text sizeWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(widthForCalc, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
CGFloat returnHeight = self.frame.size.height - self.titleLabel.frame.size.height + size.height;
CGFloat height = returnHeight < self.frame.size.height ? self.frame.size.height : returnHeight;
return height;
}
This works 100% correctly.
The cells are created obviously in cellForRowAtIndexPath and immediately configured:
if (self.items.count > 0) {
TCAnswerBuilderCell *cell = [tableView dequeueReusableCellWithIdentifier:TC_ANSWER_BUILDER_CELL forIndexPath:indexPath];
[cell configureCellWithThirdPartyObject:self.items[indexPath.row]];
return cell;
}
In configuration of the cell, my view is loaded from a nib (it's re-used elsewhere, which is why it's not directly in the cell). The cell adds it as follows:
- (void) configureCellWithThirdPartyObject:(TCThirdPartyObject *)object {
self.detailDisclosureImageView.hidden = NO;
if (!self.thirdPartyAnswerView) {
self.thirdPartyAnswerView = [TCThirdPartyAPIHelper thirdPartyAnswerViewForThirdPartyAPIServiceType:object.thirdPartyAPIType];
self.thirdPartyAnswerView.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:self.thirdPartyAnswerView];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"|[_thirdPartyAnswerView]-38-|" options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(_thirdPartyAnswerView)]];
}
[self.thirdPartyAnswerView configureViewForThirdPartyObject:object forViewStyle:TCThirdPartyAnswerViewStyleSearchCell];
}
Finally my view configuration looks like this:
- (void) configureViewForThirdPartyObject:(TCTPOPlace *)object forViewStyle:(TCThirdPartyAnswerViewStyle) style {
self.titleLabel.text = object.name;
self.addressLabel.text = [NSString stringWithFormat:#"%#, %#, %#", object.address, object.city, object.state];
self.ratingsLabel.text = [NSString stringWithFormat:#"%d Ratings", object.reviewCount];
NSString *ratingImageName = [NSString stringWithFormat:#"yelp_star_rating_%.1f.png", object.rating];
UIImage *ratingsImage = [UIImage imageNamed:ratingImageName];
if (ratingsImage) {
self.ratingImageView.image = ratingsImage;
}
if (object.imageUrl) {
[self.thumbnailImageView setImageWithURL:[NSURL URLWithString:object.imageUrl] completed:nil];
}
}
A sort of solution, but I don't understand why
My subview was designed at 320 width, but has no constraints of its own for width
The subview was added to the cell, but with horizontal constraints that look like this:
#"|[_thirdPartyAnswerView]-38-|"
The view was configured immediately after being added to the cell, meaning the text for the titleLabel was set right then.
For whatever reason, the text was laid out as if the view had the full 320 instead of 282.
The label was never updated, even though the frame of the subview was updated to 282, and there were constraints on the label that would keep it sized correctly.
Changing the size of the view in the xib to be 282 fixed the issue, because the label has the right size to begin with.
I'm still not understanding why the label doesn't re-lay out after the size of the parent view is updated when it has both leading and trailing constraints.
SOLVED
See Matt's answer below: https://stackoverflow.com/a/15514707/287403
In case you don't read the comment, the primary problem was that I was unknowingly setting preferredMaxLayoutWidth via IB when designing a view at a bigger width than it would be shown (in some cases). preferredMaxLayoutWidth is what is used to determine where the text wraps. So even though my view and titleLabel correctly resized, the preferredMaxLayoutWidth was still at the old value, and causing wrapping at unexpected points. Setting the titleLabel instead to it's automatic size (⌘= in IB), and updating the preferredMaxLayoutWidth dynamically in layoutSubviews before calling super was the key. Thanks Matt!
I'm someone who has written an app that uses autolayout of five labels in a cell in a table whose cells have different heights, where the labels resize themselves according to what's in them, and it does work. I'm going to suggest, therefore, that the reason you're having trouble might be that your constraints are under-determining the layout - that is, that you've got ambiguous layout for the elements of the cell. I can't test that hypothesis because I can't see your constraints. But you can easily check (I think) by using po [[UIWindow keyWindow] _autolayoutTrace] when paused in the debugger.
Also I have one other suggestion (sorry to just throw stuff at you): make sure you're setting the label's preferredMaxLayoutWidth. This is crucial because it's the width at which the label will stop growing horizontally and start growing vertically.
I had the same problem and solved it using a suggestion from this answer. In a subclass of UILabel I placed this code:
- (void)layoutSubviews
{
[super layoutSubviews];
self.preferredMaxLayoutWidth = self.bounds.size.width;
}
I don't understand why this is not the default behavior of UILabel, or at least why you cannot just enable this behavior via a flag.
I am a little concerned that preferredMaxLayoutWidth is being set in the middle of the layout process, but I see no easy way around that.
Also, check that you are passing integral numbers to your layout constraints in code.
For me it happened that after some calculations (e.g. convertPoint:toView:), I was passing in something like 23.99999997, and eventually this lead to a 2-line label displaying as a one-liner (although its frame seemed to be calculated correctly). In my case CGRectIntegral did the trick!
Rounding errors could kill ya :)