When I try to set height of label in cell which is set in Storyboard then it works, but when I try to set height of label which has it own .xib file then it's not working.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MainArticleCell";
MainArticleCell *cell = (MainArticleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.mainArticleTitleLabel.frame = CGRectMake(0, 0, 320, 30); // NOT WORKING
...
I connect to label successfully because whn I try to add text it works.
cell.mainArticleTitleLabel.text = #"lorem ipsum text";
Where is the problem?
UPDATE (improved explanation):
When I check before setting height is like is set over IB and after seting in code is like I set but visualy in Simulator is same.
NSLog(#"%f", cell.mainArticleTitleLabel.frame.size.height);
cell.mainArticleTitleLabel.frame = CGRectMake(0, 117, 320, 48);
NSLog(#"%f", cell.mainArticleTitleLabel.frame.size.height);
UPDATE 2
I even can change backogrund color (but seting height is not)
cell.mainArticleTitleLabel.backgroundColor = [UIColor redColor];
cell.mainArticleTitleLabel.frame = CGRectMake(0, 117, 320, 48); // NOT WORKING
The problem is that you cannot do it in the
cellForRowAtIndexPath
you have to to it in the heightForRowAtIndexPath
here is a code sample
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//in my case i get the text of the cell in an array
NSString* theText = [anArray objectAtIndex:indexPath.row];
//then calculate the texte size with standard text
CGSize textSize = [theText sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
return textSize.height;
}
if using attributed text in iOS 6 use
CGRect rectSize = [theText boundingRectWithSize:CGSizeMake(labelWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:NULL];
and return
return rectSize.size.height;
I am using this in my code and it's working for dynamic cell height.
EDIT
I read the different commentaries. It seems my answer is useless as your problem is not in returning a value in heightForRowAtIndexPath as you are already doing it. Your problem is that it's working in storyboard and not in single xib. At that point I am of no help.
After many and many triesI give up from that way and I try to add one more cell through TableView on storyboard and add custom class and it works.
Related
I'm struggling with how to dynamically size a uilabel inside a uitableviewcell and also to adjust the height of the table cell depending on the text I put into the label. I want to display a string in its entirety within the tableview cell, always at the same font size for all cells. This seems pretty standard, but I notice a lot of discussion/debate/discontent on stackoverflow. I got started with these posts:
Resize Custom cell with a UILabel on it based on content text from JSON file (#Seya's answer)
boundingRectWithSize for NSAttributedString returning wrong size (#JOM's answer)
The functions I'm trying to use are copies of what Seya did, barely modified. However, I am seeing that although the function prints out different heights for different cells, all I am seeing is 1 line of text per label even though they should show many lines. Also, strangely the text from one cell seems to display on top of another cell - not sure whether this is related.
My 2 questions: (1) Why do I only see the first line of text? (2) Why is the UILabel/cell not resizing per the different heights I see printed out in the log (or are they resizing but masked by issue #1)?
Here's the three functions I'm using (these along with a xib - could the xib be the problem?):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
JudgeCell *cell = [tableView dequeueReusableCellWithIdentifier:#"JudgeCell"];
if(!cell)
{
[tableView registerNib:[UINib nibWithNibName:#"JudgeCell" bundle:nil] forCellReuseIdentifier:#"JudgeCell"];
cell = [tableView dequeueReusableCellWithIdentifier:#"JudgeCell"];
}
cell.username.text = self.object.answerUser[indexPath.row];
cell.answer.text = self.object.answerArray[indexPath.row];
NSString *text = cell.answer.text;
CGSize constraint = CGSizeMake(50, 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];
cell.username.frame = CGRectMake(10, 10, 50, size.height); //MAX(size.height, 14.0f));
return cell;
}
-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary * attributes = #{NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle
};
CGRect textRect = [text boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
NSLog(#"size is %f ", textRect.size.height);
return textRect.size;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = self.object.answerArray[indexPath.row];
CGSize constraint = CGSizeMake(50, 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];
CGFloat height = size.height; //MAX(size.height, 14.0f);
NSLog(#"size is %f AT INDEX %d", height, indexPath.row);
return height + 20;
}
Thanks for any advice!
In the end I deleted my associated nib file, and somehow that seemed to do the trick along with the code from this tutorial (which is similar to what I already posted above):
http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/
Note that the methods in the tutorial are sometimes flagged as deprecated. If I find an updated tutorial, I will post.
I have a custom Table View Cell that loads a thumbnail, text and text's background image. I am developing a chat app and the Cell is in the Send/Receive Message screen. This cell basically shows the sent/received. Below are more details regarding the project and problem.
I have two background images. One is for sender and the other is for receiver and these images are automatically resized based on the size of the text.
When I am sending/receiving small messages (1 line), the messages are displayed correctly.
However, when I try to send/receive multiple line messages, sometime the background images are missing and sometimes the text is missing (for some images) and when I scroll, those images/text appears some times.
I am using [UIImage imagedNamed:] to load the background images each time.
In my point of view, the issue is due to Memory as around 6-8 cells are visible all the times. Kindly help me in resolving the issue.
EDIT
Adding some code
-(UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [tblView dequeueReusableCellWithIdentifier:#"myCell"];
//Setting background image view of cell
[cell.bgImageView setImage:[[UIImage imageNamed:#"chat_box2.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:40]];
String message = ........;
CGSize textSize = CGSizeMake(250, 1000);
CGSize size = [message sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:textSize];
size.width += 9;
[cell.messageText setText:message];
[cell.messageText sizeToFit];
[cell.messageText setText:message];
//Setting frames of background Image View and message Text to our desired frame (**size** is calculated in the above lines)
[cell.bgImageView setFrame:CGRectMake(79,5, cell.bgImageView.frame.size.width, size.height+18)];
[cell.messageText setFrame:CGRectMake(98, 13, size.width, size.height)];
return cell;
}
Note: The size calculation is also done in -(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath so that the cell is resized accordingly.
Yup, The issue is due to cell reusability. When you deque Tableviewcells the contents become mixup as the system tries to Re-use the old tableviewCells. What you should do is to set all the values for your cell in cellForRowAtIndexPath delegate as:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//All Initialization code
.
.
.
//Set all the values of your Custom Table View Cell here
cell.image = yourImage;
cell.text = "your text";
cell.backGroundImage = yourBackGroundImage;
cell.TimeLabel.Text = "time value";
}
Hope this should help. Free feel to ask if you have further queries.
If the cell is being displayed and the image and text are not, then the problem is related to the frame of textView and frame of the imageView.
You can try to tick clip subviews at your views (especially imageViews) and check if that makes the trick.
Anyway I suggest you to use autolayout either then defining the frame of your views.
Finally, I am able to resolve the issue myself. Below is a detailed response highlighting the cause as well as the solution for the problem.
Cause of Problem
The items [bgImageView (UIImageView) and messageText(UILabel)] were IBOutlets defined inside the Custom Cell class and connected to Cell in the Storyboard.
Whenever, we try to change frame of such elements (defined inside storyboard), the cell is not updated which was the root cause of the problem.
Solution
In order to resolve the issue, I removed the elements from storyboard and defined them inside the -initWithCoder:. Please Note that this function is called for Cells of storyboard prototype cells (instead of -initWithStyle:reuseIdentifier).
initWithCoder: This method is to be defined inside the custom UITableViewCell Class (in my case, the name of the class is MyCell
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if(self)
{
//Settings sizes to zero as they will be changed in cellForRowAtIndexPath
_bgImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
[self.contentView addSubview:_bgImageView];
_messageText = [[UILabel alloc] initWithFrame:CGRectZero];
_messageText.backgroundColor = [UIColor clearColor];
[_messageText sizeToFit];
[_messageText setFont:[UIFont systemFontOfSize:12]];
[_messageText setNumberOfLines:0];
[self.contentView addSubview:_messageText];
}
return self;
}
The heightForRowAtIndexPath* and *cellForRowAtIndexPath: are also given for reference.
heightForRowAtIndexPath:
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *message = .......;
CGSize size = [self getSize:message]; //look below for getSize:
size.height += 18 + 15; //to cater for padding (top & bottom).
return height;
}
cellForRowAtIndexPath:
-(UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [tblView dequeueReusableCellWithIdentifier:#"msgCell"];
NSString *message = ......;
CGSize size = [self getSize:message]; //look below for getSize:
cell.messageText.text = message;
[cell.messageText setFrame:CGRectMake(98, 13, size.width, size.height)];
[cell.bgImageView setFrame:CGRectMake(79,5, CELL_MESSAGE_WIDTH+32, size.height+18)]; //write #define CELL_MESSAGE_WIDTH 200 at the top of the file (below include statements)
[cell.bgImageView setImage:[[UIImage imageNamed:#"img.png"] stretchableImageWithLeftCapWidth:11 topCapHeight:23]];
return cell;
}
getMaxSize:
-(CGSize)getSize:(NSString*)str
{
CGSize maxSize = CGSizeMake(CELL_MESSAGE_WIDTH, 1000);
CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
return size;
}
Try to set the image, text and all the content inside of MyCell not in -tableView: cellForRowAtIndexPath: delegate method.
I can see you mark yourself as solved. If it works that's great. However there are couple of thing you should definitely improve and change. There are my suggestions.
I don't think you have to do anything in initWithCoder:. You can leave to storyboard to handle. Here is the code how I think you should do:
MyCell.h
// define enum for type of cell
typedef NS_ENUM(NSInteger, MyCellType) {
MyCellTypeSender,
MyCellTypeReceiver
};
#interface MyCell : UITableViewCell
#property (nonatomic, assign) MyCellType cellType;
#property (nonatomic, strong) NSString *message;
- (void)fitToSize:(CGSize)size;
#end
MyCell.m
#implementation MyCell
// As you can see image is implemented inside the cell in setter of cellType
-(void)setCellType:(MyCellType)cellType {
if (_cellType != cellType) {
_cellType = cellType;
UIImage *bgImage = [UIImage imageNamed:(cellType == MyCellTypeReceiver) ? #"receiverImg" : #"senderImg"];
self.bgImageView.image = [bgImage stretchableImageWithLeftCapWidth:11 topCapHeight:23];
}
}
-(void)setMessage:(NSString *)message {
if (![message isEqualToString:_message]) {
_message = message;
self.messageLabel.text = _message;
}
}
-(void)fitToSize:(CGSize)size {
self.messageLabel.frame = CGRectMake(98, 13, size.width, size.height);
self.bgImageView.frame = CGRectMake(79,5, size.width+32, size.height+18);
}
#end
In your file where you implement delegate and data source method for table use following code:
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *message = #"some message ....";
CGSize size = [self sizeForText:message];
return size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:#"myCell"];
CGRect cellFrame = [tableView rectForRowAtIndexPath:indexPath]; // Do not calculate the size again. Just grab cell frame from current indexPath
[cell fitToSize:cellFrame.size]; // You set the content of the cell in MyCell by passing size of cell
cell.cellType = MyCellTypeRecever; // Or MyCellTypeSender whichever you decide
cell.message = #"some message ....";
return cell;
}
-(CGSize)sizeForText:(NSString*)str {
NSDictionary *attributes = #{NSFontAttributeName: [UIFont systemFontOfSize:18.f]};
CGSize maxSize = CGSizeMake(CELL_MESSAGE_WIDTH, 1000);
// This is the method you should use in order to calculate the container size
// Avoid using -sizeWithFont:constrainedToSize:lineBreakMode: as it is depracated in iOS7
CGRect rect = [str boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:NULL];
return rect.size;
}
Some lines are commented. As you can see most of the important code landed in MyCell subclass of UITableVieCell.
Also please note -sizeWithFont:constrainedToSize:lineBreakMode: is deprecated and use -boundingRectWithSize:options:attributes:context:
I have a prototype cell inside my UITableView which contains a UILabel. I want to dynamically change the size of the label (and the cell) depending on the size of the text in the label.
I create the prototype cell in cellForRowAtIndexPath like this:
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
return cell;
Then my ProgramDetailCell has the following implementation:
#implementation ProgramDetailCell
- (void)layoutSubviews {
[super layoutSubviews];
[self.descriptionLabel sizeToFit];
}
#end
The first time the cell is displayed, layoutSubviews is called, but the descriptionLabel does not get resized. However, if I scroll down the table and back up again, the "reused" cell appears with the label correctly resized!
Why does it not work the first time the cell is displayed - and what do I need to do to fix it.
Thanks in advance!
In xib, go to first tab, under Interface Builder Document , uncheck use Auto Layout box.
It doesn't work because you are using auto layout. You need some auto layout way to achieve this.
Here's the solution.
Step 1 :
Have the UILabel Pinned to Top and Bottom of the UITableViewCell. You can achieve this through the Interface Builder by having Vertical Constraint on UILabel from top and bottom of the cell. This will make the UILabel increase in height if the cell's height increase or vice versa.
Step 2:
In your UIViewController in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath method calculate the size of the UITableViewCell.
You can calculate it using :
CGRect textFrame = [YourText boundingRectWithSize:CGSizeMake(width of the label, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:Your Font} context:nil];
now return the textFrame.size.height + padding if present.
Step 3 :
You will achieve what you wanted --- "dynamically change the size of the label (and the cell) depending on the size of the text in the label" after compiling and running even for the first time.
After retrieving all data from server you can get height of that UILabel using this method.
CGSize maximumSize = CGSizeMake(210, 9999);
for (int i = 0; i < [_arrProductList count]; i++) {
float row_height = 0.0f;
ProductInformation *product_obj = [_arrProductList objectAtIndex:i];
CGSize desc_size = [self measureHeightForText:product_obj.product_desc forFont: [UIFont systemFontOfSize:14] forSize:maximumSize];
row_height = row_height + desc_size.height;
// [_arrRowHeights addObject:[NSString stringWithFormat:#"%f", row_height]]; You can take it into array.
}
[tableView reloadData];
And here i have given description of measureHeightForText:. This logic is working in all iOS5,iOS6,iOS7.
-(CGSize)measureHeightForText:(NSString *)strText forFont:(UIFont *)font forSize:(CGSize)size{
if (!testingLabel) {
testingLabel = [[UILabel alloc] init];
// testingLabel.font = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
testingLabel.text = #"";
testingLabel.numberOfLines = 0;
}
testingLabel.text =strText;
testingLabel.font = font;
CGSize expectedSize = [testingLabel sizeThatFits:size];
return expectedSize;
}
And then update size of your label according it. This is working fine for me. I am using it.
Because when layoutSubviews is called your descriptionLabel's text is not set yet. And when you scroll, the text is set. So it is correct now.
I suggest you call sizeToFit after you set the text.
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
[cell.descriptionLabel sizeToFit];
return cell;
Call this in heightForRowAtIndexPath and manually calculate the height
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
[cell.descriptionLabel sizeToFit];
return cell.descriptionLabel.frame.size.height+cell.descriptionLabel.frame.origin.y;
You can use below code:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
If your requirement is dynamically changing label height mean follow the below link. When we need to change height of label we need to change the row height also:
Resizing UILabel not quite working
Use below code for dynamic height set in cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *messagetext=[NSString stringWithFormat:#"%#",[[arryStoryView objectAtIndex:indexPath.row] valueForKey:#"messagetext"]];
CGSize StoryTextSize= [messagetext sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
int TotalHeight;
TotalHeight= StoryTextSize.height + 10;
return TotalHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell1";
UITableViewCell *cell=[tblSendMsg dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *storytext=[NSString stringWithFormat:#"%#",[[arryStoryView objectAtIndex:indexPath.row] valueForKey:#"storytext"]];
CGSize StoryTextSize = [storytext sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
lblStoryText.frame=CGRectMake(5, 25, [[UIScreen mainScreen] bounds].size.width-10, StoryTextSize.height+30);
int nooflines=StoryTextSize.height/16;
int i= StoryTextSize.height;
if(i%16 !=0)
{
nooflines=nooflines+1;
}
lblStoryText.numberOfLines=nooflines;
lblStoryText.font=[UIFont fontWithName:#"Georgia" size:17.0f];
lblStoryText.text=[NSString stringWithFormat:#"%#",storytext];
return cell;
}
If you are using autolayout, modifying the frame will have no effect.
Instead, you should modify the constraints.
I have a UITableView that uses prototype cells. The cells have a custom class called dataCell. The custom cells also have three UILabels:idLabel, contLabel, and expLabel. The cells properly resize based on the amount of text in expLabel; however, I cannot get the label itself to resize. Some labels resize when I scroll down; however, they also revert to showing only two lines and omitting text when I scroll back up. Here is my code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
dataCell *cell = (dataCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// the rest of your configure cell
// First Cell Label
[cell.idLabel setText:[idData objectAtIndex:indexPath.row]];
cell.idLabel.numberOfLines = 0;
// Second Cell Label
[cell.contLabel setText:[conData objectAtIndex:indexPath.row]];
cell.contLabel.numberOfLines = 0;
// Third Cell Label
[cell.expLabel setText:[expData objectAtIndex:indexPath.row]];
cell.expLabel.numberOfLines=0;
CGSize expectedLabelSize = [cell.expLabel.text sizeWithFont:cell.expLabel.font constrainedToSize:CGSizeMake(220, FLT_MAX) lineBreakMode:cell.expLabel.lineBreakMode];
cell.expLabel.frame=CGRectMake(cell.expLabel.frame.origin.x, cell.expLabel.frame.origin.y, expectedLabelSize.width, expectedLabelSize.height);
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
dataCell *cell = (dataCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CGSize maximumLabelSize = CGSizeMake(220, FLT_MAX);
[cell.expLabel setText:[expData objectAtIndex:indexPath.row]];
CGSize expectedLabelSize = [cell.expLabel.text sizeWithFont:cell.expLabel.font constrainedToSize:maximumLabelSize lineBreakMode:cell.expLabel.lineBreakMode];
if (expectedLabelSize.height<43) {
expectedLabelSize.height=43;
}
return expectedLabelSize.height; }
Any help would be much appreciated
If you are using a storyboard and a UITableViewCell then you can just change the auto resizing mask, but if you are doing it programmatically then you will have to set the calculate the text width and height and reset the frame of the labels,
UILabel* label = [[UILabel alloc] init];
UIFont* font = label.font;
CGSize maxContentSizeForText = CGSizeMake(maxTextWidth, maxTextHeight);
CGSize stringTextSize = [string sizeWithFont:font constrainedToSize:maxContentSizeForText lineBreakMode:NSLineBreakByWordWrapping];
[label setFrame:CGRectMake(xPosition, yPosition, stringTextSize.width, stringTextSize.height);
[label setNumberOfLines:1000];
your label is probably a property from a xib file or storyboard, and the number of lines is just saying that you want the label to get really really big, since we can't say "infinite" i just generally use 1000 indicating 1000 lines of text maximum
With the help of the good people of StackOverflow, I have these two methods:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault)
reuseIdentifier:#"business"];
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
NSLog(businessPrivacy);
// FIND IF THE BUSINESS PLAN IS PRIVATE OR NOT.
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, MAX(size.height, 44.0f) + 20.0f)];
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = comment;
[cell.contentView addSubview:label];
return cell;
}
//Cell size for word wrapping.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (10 * 2);
}
The effect that they have is reducing font size from default font size, and dynamically resizing to ALMOST fit the entire text of a comment no matter how long that text might be.
What I am confused with is that I have some of the same code in both methods, and I dont know how it really should look like. I do know both methods are getting called, but not sure what should be where so they would work properly.
Thanks in advance for advice.
It looks like you need them in both. I have rewritten your code with comments so that you can make sense of it:
//This function is used to create the cell and the content of the cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Here you are allocating a new cell with a reuse identifier. This is only needed if
//you plan on reusing the cells and using [tableView dequeueReusableCellWithIdentifier:cellIdentifier]
//Reusable cells will save you some memory and make your tableview work more smoothly,
//however here you are not selecting from the reusable pool, and are instead making a new cell each time
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault)
reuseIdentifier:#"business"];
//This is pulling the text for the comment, it is obviously necessary
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
NSLog(businessPrivacy);
// FIND IF THE BUSINESS PLAN IS PRIVATE OR NOT.
// This is creating a constraint size for the label you are making
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
// This is determining the size that you will need for the label based on the comment
// length and the contraint size
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// Here you are creating your label and initializing it with the frame that you have
// determined by your size calculations above
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, MAX(size.height, 44.0f) + 20.0f)];
// setting up the label properties
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
label.text = comment;
// adding the label view to the cell that you have created
[cell.contentView addSubview:label];
// return the cell for the table view
return cell;
}
//Cell size for word wrapping.
//This method will determine how tall each row needs to be.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
//Here you are getting the comment again. This is necessary to determine how tall you need
//the cell to be
NSString *comment = [[items_array objectAtIndex:[indexPath row]] objectForKey:(#"comment")];
// Again you are getting the constraints because you are going to us this size
// to constrain the height of the cell just like you determined the size for the label.
CGSize constraint = CGSizeMake(320 - (10 * 2), 20000.0f);
// Again, determining the size that we will need for the label, because it will drive
// the height of the cell
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// Finally, we can determine the height for the cell!
CGFloat height = MAX(size.height, 44.0f);
// return the height, which is the height of the label plus some extra space to make
// it look good.
return height + (10 * 2);
}
So basically, the cellForRow... function creates the content of the cell and the heightForRow... function determines the height. You need all of that information in both of them because the cell function only creates the content of the cell while the height function creates the height of the row and the comment, constraint, and size are all important in determine the label size for the cell content and the height of the cell.
So heightForRowAtIndexPath, as its name suggests, only deal with the height of the cells. i.e. the return value (a CGFloat) of that function is the height of the cell at the specified indexpath.
cellForRowAtIndexPath on the other hand sets up the actual cell, including all its subviews. What happens is, say some cells have a 5-line UILabel and some have 1-line. Then You need to adjust the size of the cell in heightForRowAtIndexPath, but at the same time you also need to adjust the size of the UILabel within the cell in cellForRowAtIndexPath. The latter will not automatically happen. You need to take care of both yourself.
If you have to write the same code two or more times, you should consider extracting the duplicate code into a method or function. But you have some other problems we should address.
Let's declare some constants so we don't have to repeat numbers all over the code:
static const CGFloat kLabelMargin = 10.0f;
static const CGFloat kLabelWidth = 320.0f - 2.0f * kLabelMargin;
One line you have duplicated in both methods looks up the comment for a row. Let's make a method to do that:
- (NSString *)commentForRowAtIndexPath:(NSIndexPath *)indexPath {
return [[items_array objectAtIndex:[indexPath row]] objectForKey:#"comment"];
}
The other duplicated code computes the height of the row, so let's make a function to return that:
static CGFloat heightForComment(NSString *comment) {
CGSize constraint = CGSizeMake(kLabelWidth, 20000.0f);
CGSize size = [comment sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
return MAX(size.height, 44.0f) + 2.0f * kLabelMargin;
}
Now we can rewrite your tableView:heightForRowAtIndexPath: method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return heightForComment([self commentForRowAtIndexPath:indexPath]);
}
Finally, let's rewrite your tableView:cellForRowAtIndexPath: method. We will make it properly reuse cells (to avoid wasting memory), and we'll make it use the new method and function we created.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *const kReuseIdentifier = #"business";
static const NSInteger kLabelTag = 1;
NSLog(#"%#", businessPrivacy);
// FIND IF THE BUSINESS PLAN IS PRIVATE OR NOT.
NSString *comment = [self commentForRowAtIndexPath:indexPath];
CGRect labelFrame = CGRectMake(0, 0, kLabelWidth, heightForComment(comment));
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseIdentifier];
UILabel *label;
if (cell) {
label = (UILabel *)[cell.contentView viewWithTag:kLabelTag];
label.frame = labelFrame;
} else {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kReuseIdentifier];
label = [[UILabel alloc] initWithFrame:labelFrame];
label.tag = kLabelTag;
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
[cell.contentView addSubview:label];
}
label.text = comment;
return cell;
}