In my UITableViewCells I am displaying text of varying lengths. To accomodate larger amounts of text and while also not requiring small texts amounts to be in huge table cells I am setting the height of the rows here...
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float padding = 40.0f;
CGSize constraintSize;
constraintSize.width = 320.0f - padding - padding;
constraintSize.height = MAXFLOAT;
CGSize theSize = [thisrowstext sizeWithFont:[UIFont systemFontOfSize:14.0f]
constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
if(theSize.height < 24.0f) return 44.0f;
else return theSize.height + 20.0f;
}
...it works well, unfortunately the textLabel's width seems to be affected too with some textLAbels (depending on row count) being pushed in a few pixels. I've tried setting indentation values, but that doesn't work. Has anyone else encountered this?
EDIT: I'm adding the layoutSubviews method of my UITableViewCell subclass that i'm using (no NIB).
- (void)layoutSubviews
{
[super layoutSubviews];
if (self.hideImage)
{
self.imageView.alpha = 0.0f;
self.imageView.frame = CGRectMake(-40.0f, 1.0f, 40.0f, 40.0f);
CGRect frame = self.textLabel.frame;
self.textLabel.frame = CGRectMake(frame.origin.x - 40.0f, frame.origin.y, frame.size.width + 40.0f, frame.size.height);
[self.textLabel setNeedsLayout];
}
else
{
self.imageView.alpha = 1.0f;
self.imageView.frame = CGRectMake(1.0f, 1.0f, 40.0f, 40.0f);
[self.textLabel setNeedsLayout];
}
}
EDIT: Also adding cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *TableCellViewWithHidableImageIdentifier = #"TableCellViewWithHidableImage";
TableCellViewWithHidableImage *cell = (TableCellViewWithHidableImage *)[tableView dequeueReusableCellWithIdentifier:TableCellViewWithHidableImageIdentifier];
if (cell == nil)
{
cell = [[[TableCellViewWithHidableImage alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableCellViewWithHidableImageIdentifier] autorelease];
}
cell.hideImage = NO;
cell.imageView.image = [UIImage imageNamed:#"empty.png"];
cell.textLabel.font = [UIFont systemFontOfSize:16.0f];
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = #"whatever";
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
It's hard to tell without seeing how you generate your table cells. Do you use a nib for your cells? I've found it much easier to use a nib for custom table cells, so try that if you aren't already.
I suspect you may have a problem with your autoresizeMask on one or more of your table cells' subviews.
This is a bit of a guess, but it looks to me like it is the imageView on the left hand side of the cell. Seems like as the cell gets taller, it gets wider (trying to maintain aspect ratio?) and this is pushing your text to the right. What's odd is you image is not stretched. Might be worthwhile looking at what is happening to that image view during layoutSubviews. If your custom cell does not implement this method, maybe the base class' implementation is doing something you don't expect. You could override it and NSLog to the frame of the image view before and after the a call to [super layoutSubviews] to see whats going on.
Related
I'm trying to change the height of a UILabel depending on how much text is in the label.
I can calculate the size required for the label but when I try to set the UILabel frame it just doesn't change.
Below is my code.
Even if I replace size.height in the last line to something like 500 the size of the UILabel frame doesn't change
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"GameItemCell";
GameItemCell *cell = (GameItemCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"GameItemCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
GameItem* item = [_hunt.gameItems objectAtIndex: indexPath.row];
cell.itemHeaderLabel.text = [NSString stringWithFormat:#"#%d - (%d pts)", indexPath.row+1, item.itemPoints];
UILabel* textLabel = cell.itemTextLabel;
textLabel.text = item.itemText;
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGRect frame = cell.itemTextLabel.frame;
CGSize textSize = { frame.size.width, 20000.0f };
CGSize sizeOneLine = [#"one line" sizeWithFont:cell.itemTextLabel.font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGSize cellTextSize = [item.itemText sizeWithFont:cell.itemTextLabel.font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGSize sizeOneLineSpacing = CGSizeMake(sizeOneLine.width, sizeOneLine.height + 3);
NSInteger lines = cellTextSize.height / sizeOneLine.height;
CGSize size = CGSizeMake(frame.size.width, lines * sizeOneLineSpacing.height);
textLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, size.width, size.height);
return cell;
}
You must set the frame of your label in GameItemCell inside -(void)layoutSubviews
Instead of doing all that hard work, try it like:
textLabel.numberOfLines = 0;
textLabel.text = textString;
[textLabel sizeToFit];
remember sizeToFit respect your labels default width, so set width according to your requirement. And then Height will be managed by the sizeToFit method.
In the end you will need to put something like these two methods in your UITableViewCell subclass:
// call this method on your cell, during cellForRowAtIndexPath
// provide your resizing info (frame, height, whatever)
- (void) updateLabelFrame:(CGRect)newLabelFrame {
self.resizedLabelFrame = newLabelFrame;
[self setNeedsLayout];
}
// the actual resize happens here when UIKit gets around to it
- (void) layoutSubviews {
[super layoutSubviews];
self.myLabel.frame = self.resizedLabelFrame;
}
You have missed numberOfLines property to set.
Add :
textLabel.numberOfLines = 0;
CGRect labelFrame = myLabel.frame;
labelFrame.size = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:CGSizeMake(myLabel.frame.size.width, CGFLOAT_MAX)
lineBreakMode:myLabel.lineBreakMode];
cell.textLabel.frame = labelFrame;
numberOfLines
The maximum number of lines to use for rendering text.
The default value for this property is 1. To remove any maximum limit, and use as many lines as needed, set the value of this property to 0.
tack a look UILabel Class Reference
According to your question you can set no of lines
Now number of lines is not set to your label, so set it,
textLabel.numberOfLines = lines;
Yeah, for multiple lines use textLabel.numberOfLines = 0; in cellForRowAtIndexPath
But Still you need to change the height of the cell too:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Calculate new cell height too as you are doing in cellForRowAtIndexPath
return YOUR_SIZE;;
}
Try this :
NSString *text1 = shareObjC.commentText;
CGSize constraint1 = CGSizeMake(280 - (size.width + 5), 2000);
CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:UILineBreakModeWordWrap];
UILabel *lblComment = [[[UILabel alloc] initWithFrame:CGRectMake(posx,posy,size1.width,size1.height)] autorelease];
lblComment.lineBreakMode = UILineBreakModeWordWrap;
lblComment.numberOfLines = size1.height/15;
[lblComment setFont:[UIFont systemFontOfSize:12]];
lblComment.text = text1;
[cell.viewLikeComment addSubview:lblComment];
I'm trying to resize a UITextView that I have in a UITableViewCell. I want to resize the UITableViewCell accordingly also. My UITableViewCell resizes properly, but the UITextView does not. It ends up being just two lines instead of sizing to the the correct size. When I initialize it in the cellForRowAtIndexPath method, it looks like:
UITextView *notesTextView = [[UITextView alloc] initWithFrame:CGRectMake(83, 12, TEXTVIEW_WIDTH, 22)];
notesTextView.tag = TEXTVIEW_TAG;
notesTextView.delegate = self;
[cell.contentView addSubview:notesTextView];
When I try to modify it in the textView delegate method, I do:
CGSize size = [textView.text sizeWithFont:textView.font constrainedToSize:CGSizeMake(TEXTVIEW_WIDTH, 460) lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"size: %#", NSStringFromCGSize(size)); // has the correct size
if (size.height > self.notesRowHeight) {
self.notesRowHeight = size.height;
UITextView *aTextView = (UITextView *)[self.view viewWithTag:TEXTVIEW_TAG];
CGRect textViewFrame = CGRectMake(aTextView.frame.origin.x, aTextView.frame.origin.y, TEXTVIEW_WIDTH, size.height);
aTextView.frame = textViewFrame;
aTextView.contentSize = size;
[aTextView sizeToFit];
[aTextView sizeThatFits:size];
NSLog(#"%#", NSStringFromCGRect(aTextView.frame)); // has the correct height
So what ends up happening is the tableView resize properly, and even though the textView frame is the correct size (e.g. {{83, 12}, {197, 120}}), the textView only has 2 lines. It does not end up taking the size of the UITableViewCell like I intended.
EDIT: When I try to just resize the frame for the UITextView in a normal UIView that is not a UITableViewCell, it works just fine. So I'm not sure what's different in this case.
I found the answer. I should not reload the row, but just call
[tableView beginUpdates];
[tableView endUpdates];
More information can be found at:
UITextView in a UITableViewCell smooth auto-resize shows and hides keyboard on iPad, but works on iPhone
I found the best way to solve this.
First off, of course, you're going to want to create your UITextView and add it to your cell's contentView. I created an instance variable of UITextView called "cellTextView" Here is the code that I used:
- (UITableViewCell *)tableView:(UITableView *)tableView fileNameCellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
if (!cellTextView) {
cellTextView = [[UITextView alloc] initWithFrame:CGRectMake(5.0, 5.0, cell.bounds.size.width - 30.0, cell.bounds.size.height - 10.0)]; // I use these x and y values plus the height value for padding purposes.
}
[cellTextView setBackgroundColor:[UIColor clearColor]];
[cellTextView setScrollEnabled:FALSE];
[cellTextView setFont:[UIFont boldSystemFontOfSize:13.0]];
[cellTextView setDelegate:self];
[cellTextView setTextColor:[UIColor blackColor]];
[cellTextView setContentInset:UIEdgeInsetsZero];
[cell.contentView addSubview:cellTextView];
return cell;
}
Then, create an int variable called numberOfLines and set the variable to 1 in your init method. Afterwards, in your textViewDelegate's textViewDidChange method, use this code:
- (void)textViewDidChange:(UITextView *)textView
{
numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;
float height = 44.0;
height += (textView.font.lineHeight * (numberOfLines - 1));
CGRect textViewFrame = [textView frame];
textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
[textView setFrame:textViewFrame];
[self.tableView beginUpdates];
[self.tableView endUpdates];
[cellTextView setContentInset:UIEdgeInsetsZero];
}
Finally, paste this code into your heightForRowAtIndexPath method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float height = 44.0;
if (cellTextView) {
height += (cellTextView.font.lineHeight * (numberOfLines - 1));
}
return height;
}
I will give you an different view....
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.
.
if(_YOUR_ROW_ && _YOUR_SECTION_)
{
cell.textView.text = Text_Of_TextView;
}
.
.
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
.
.
if(_YOUR_ROW_ && _YOUR_SECTION_)
{
UIFont * FontSize = [UIFont systemFontOfSize:14.0];
CGSize textSize = [Text_Of_TextView sizeWithFont:FontSize constrainedToSize:CGSizeMake(Width_OF_textView, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
return textSize.height+PADDING;
}
.
.
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
[Text_Of_TextView setText:textView.text];
CGRect frame = textViewInRow.frame;
frame.size.height = textViewInRow.contentSize.height;
textViewInRow.frame = frame;
[TableView_InView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:_YOUR_ROW_ inSection:_YOUR_SECTION_]] withRowAnimation:UITableViewRowAnimationNone];
}
and also dont forget to implement auto resizing behaviour for textview
This is a simple project that demonstrates how to use auto layout to resize the cells as of iOS 8. Almost no special code required. See readme.md for key points.
project on github
I am trying to resize the height of my row in UITableView based on the text length. I have the following code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText =[[topics objectAtIndex:indexPath.row] name];
UIFont *cellFont = [UIFont fontWithName:#"ArialMT" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"ArialMT" size:17.0];
}
}
However, it messes up with the UIImageView and the UIDetailText, image shown below:
How do I fix this?
I've tried:
[cell.imageView setContentMode:UIViewContentModeScaleToFill];
[cell.imageView setFrame:CGRectMake(0, 0, 16,16)];
[cell.imageView setBounds:CGRectMake(0, 0, 16,16)];
[cell.imageView setAutoresizingMask:UIViewAutoresizingNone];
[cell.imageView setAutoresizesSubviews:NO];
and none seems to work
The work of changing cell's subviews' frames is done in - (void)layoutSubviews of UITableViewCell class, so if you want alter that behavior you can subclass common UITableViewCell and then do smth like:
#implementation MyTableViewCell
- (void)layoutSubviews {
[super layoutSubviews];
self.imageView.frame = CGRectMake( -- your own size -- );
}
#end
Instead of subclassing as suggested by others, you could also add your own subviews to the cell’s content view.
From Customizing Cells:
If you want the cell to have different
content components and to have these
laid out in different locations, or if
you want different behavioral
characteristics for the cell, you have
two alternatives. You can add subviews
to the contentView property of the
cell object or you can create a custom
subclass of UITableViewCell.
You should add subviews to a cell’s content view when your content layout can be specified entirely with the appropriate autoresizing settings and when you don’t need to modify the default behavior of the cell.
You should create a custom subclass when your content requires custom layout code or when you need to change the default behavior of the cell, such as in response to editing mode.
See this example:
#define CUSTOM_IMAGE_TAG 99
#define MAIN_LABEL 98
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UIImageView *customImageView = nil;
UILabel *mainLabel = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
customImageView = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 40.0f, 40.0f)] autorelease];
customImageView.tag = CUSTOM_IMAGE_TAG;
[cell.contentView addSubview:customImageView];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(60.0f, 10.0f, 100.0f, 21.0f)] autorelease];
mainLabel.tag = MAIN_LABEL;
mainLabel.numberOfLines = 0;
[cell.contentView addSubview:mainLabel];
} else {
customImageView = (UIImageView *)[cell.contentView viewWithTag:CUSTOM_IMAGE_TAG];
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAIN_LABEL];
}
// Configure the cell.
CGRect frame = mainLabel.frame;
frame.size.height = ... // dynamic height
mainLabel.frame = frame;
return cell;
}
Obviously, you still need to implement tableView:heightForRowAtIndexPath:.
I think the built in imageView will ignore your attempts to resize it. Subclass UITableViewCell and add your own custom UIImageView to it. Then you can control all aspects of your image view.
-- wisenomad's solution will work without having to add your own custom image view and labels. --
You will also have to change the frame of the textLabel. Here is an example.
- (void)layoutSubviews {
[super layoutSubviews];
float sideLength = self.frame.size.height;
self.imageView.frame = CGRectMake(0.0, 0.0, sideLength, sideLength);
CGRect textLabelFrame = self.textLabel.frame;
self.textLabel.frame = CGRectMake(44.0, textLabelFrame.origin.y, textLabelFrame.size.width - 44.0 + textLabelFrame.origin.x, textLabelFrame.size.height);
}
I want to have my text in my UITableViewCell to be a little bit to the right. In other words I want to have an x-offset. Is this even possble? Do I have to create a custom cell just because of this?
You could use cell.indentationLevel and if needed cell.indentationWidth instead of custom UITableViewCell for this.
You can try this :
[cell setIndentationLevel:SOME_NUMBER];
[cell setIndentationWidth:SOME_OTHER_NUMBER];
A simple solution is you can change the frame of the textLabel.
CGRect textLabelFrame = cell.textLabel.frame;
textLabelFrame.origin.x += xOffset;
textLabelFrame.size.width -= xOffset;
cell.textLabel.frame = textLabelFrame;
I've also done this by creating a custom UILabel that supports edgeInsets similar to a UIButton. This is a better solution b/c you can layout the label to correct size but the above will work if you have simple needs.
[EDIT 1/2: fixed typo w/ CGRect]
[EDIT 3: fixed typo setting modified frame]
[EDIT 4: need a simple subclass]
Mea culpa. I was wrong that you can do this in tableView:cellForRowAtIndexPath. The UITableViewCell layout happens after the tableView delegate/datasource has a chance to customize the cell. I've tested the implementation below, it works.
Do as I say above but create a (simple) subclass of UITableViewCell that adds the xOffset in layoutSubviews. If you do this, you can also add an xOffset property that you can set in tableView:cellForRowAtIndexPath:.
#implementation XOffsetCell
// assumes property xOffset is defined and synthesized
- (void) layoutSubviews
{
[super layoutSubviews];
CGRect textLabelFrame = cell.textLabel.frame;
textLabelFrame.origin.x += self.xOffset;
textLabelFrame.size.width -= self.xOffset;
cell.textLabel.frame = textLabelFrame;
}
#end
The solution that suggested adding a custom UILabel to cell.contentView is also a good solution. I saw your comment that it obscures the built-in textLabel but that's the whole point. You would not use the built-in label anymore, use the custom label instead.
I'm not trolling for votes, but wanted to show what the code provided by #iPhone monster "should" look like. His solution is a valid option. If you add the label to the cell after the if (cell == nil) as he did you will be continually adding labels to dequeued cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(50.0f, 10.0f, 150.0f, 20.0f)];
lbl.tag = OffsetLabelTag; // define this as a constant
[cell.contentView addSubview:lbl];
[lbl release];
}
UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:OffsetLabelTag];
[lbl setText:#"test text"];
return cell;
}
You can do that with Autolayouts:
UITableViewCell *cell = [UITableViewCell new];
cell.textLabel.translatesAutoresizingMaskIntoConstraints = NO;
[cell.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|-(indentation)-[textLabel]-(indentation)-|"
options:0
metrics:#{#"indentation": #35}
views:#{#"textLabel": cell.textLabel}]];
Or using Parus lib:
[cell.contentView addConstraints:(PVVFL(#"H:|-(indentation)-[textLabel]-(indentation)-|")
.withViews(#{#"textLabel": textLabel})
.metrics(#{#"indentation": #35}).asArray)];
Other way:
- (NSInteger)tableView:(UITableView *)tableView
indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
return intOffset; // but is like '\t', not points
}
There is another not very pretty and smart way : ) Position of Label in TableViewCell depends on size of image assigned to cell.imageView.image property. So if you want your text to move right you can add several blank pixel columns to image in cell.
Based off of https://stackoverflow.com/a/5659826/1058199, here is a Swift version.
This works within the cell to ONLY move the textLabel to the right. Swift 5.4
override func layoutSubviews() {
super.layoutSubviews()
var textLabelFrame = self.textLabel?.frame
textLabelFrame?.origin.x += 32
textLabelFrame?.size.width -= 32
self.textLabel?.frame = textLabelFrame ?? CGRect.zero
}
Will cell.textLabel.textAlignment = UITextAlignmentCenter; be enough for you. It could align the text to the center creating that space for you
I have a UITextView in a UITableViewCell contentview and allow the cell to autoresize so that the entered text is fully shown - what I am trying to accomplish is an autoresizing cell like the native iOS4 Contacts app has, when you enter "notes" for contact - i.e. when the contentSize of the textView changes - I call reloadRowsAtIndexPaths and in the delegate's heightForRowAtIndexPath I provide the new height for row - this does the job, however it is not nice and smooth like the contact's app - I am almost sure Apple uses some undocumented trick in that app to make the cell's contentView expand smooth and animated without calling reloadRowsAtIndexPaths. My question is how would you suggest to implement such functionality? I hope I didn't miss any details in explanation.
Try this code below, it will be help. You don't have to use any reload functions like reloadRowsAtIndexPaths.
// textview delegate
- (void)textViewDidChange:(UITextView *)textView {
if (contentView.contentSize.height > contentRowHeight) {
contentRowHeight = contentView.contentSize.height;
[theTableView beginUpdates];
[theTableView endUpdates];
[contentView setFrame:CGRectMake(0, 0, 300.0, contentView.contentSize.height)];
}
}
// tableview delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height;
if (indexPath.row == 0)
height = kTitleRowHeight;
else
height = contentRowHeight;
return height;
}
I found the best way to solve this.
First off, of course, you're going to want to create your UITextView and add it to your cell's contentView. I created an instance variable of UITextView called "cellTextView" Here is the code that I used:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
if (!cellTextView) {
cellTextView = [[UITextView alloc] initWithFrame:CGRectMake(5.0, 5.0, cell.bounds.size.width - 30.0, cell.bounds.size.height - 10.0)]; // I use these x and y values plus the height value for padding purposes.
}
[cellTextView setBackgroundColor:[UIColor clearColor]];
[cellTextView setScrollEnabled:FALSE];
[cellTextView setFont:[UIFont boldSystemFontOfSize:13.0]];
[cellTextView setDelegate:self];
[cellTextView setTextColor:[UIColor blackColor]];
[cellTextView setContentInset:UIEdgeInsetsZero];
[cell.contentView addSubview:cellTextView];
return cell;
}
Then, create an int variable called numberOfLines and set the variable to 1 in your init method. Afterwards, in your textViewDelegate's textViewDidChange method, use this code:
- (void)textViewDidChange:(UITextView *)textView
{
numberOfLines = (textView.contentSize.height / textView.font.lineHeight) - 1;
float height = 44.0;
height += (textView.font.lineHeight * (numberOfLines - 1));
CGRect textViewFrame = [textView frame];
textViewFrame.size.height = height - 10.0; //The 10 value is to retrieve the same height padding I inputed earlier when I initialized the UITextView
[textView setFrame:textViewFrame];
[self.tableView beginUpdates];
[self.tableView endUpdates];
[cellTextView setContentInset:UIEdgeInsetsZero];
}
Finally, paste this code into your heightForRowAtIndexPath method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
float height = 44.0;
if (cellTextView) {
height += (cellTextView.font.lineHeight * (numberOfLines - 1));
}
return height;
}