I have a UITableViewCell that is dynamically sized based on the content in it. I do this in heightForRowAtIndexPath as follows:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
NSDictionary *fields = self.messageDetailsDictionary[#"fields"];
NSString *cellText = fields[#"message_detail"];
UIFont *cellFont = [UIFont systemFontOfSize:14.0];
CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width - 50.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 20.0f;
} else {
return tableView.rowHeight;
}
}
In cellForRowAtIndexPath I customise the cell as follows:
case 1:{
UITableViewCell *cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DetailCell"];
if (cell == nil) {
cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DetailCell"];
}
NSDictionary *fields = self.messageDetailsDictionary[#"fields"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.font = [UIFont systemFontOfSize:14.0];
cell.textLabel.numberOfLines = 0; // This means multiline
cell.textLabel.text = fields[#"message_detail"];
return cell;
}
This all works fine, however I want the content of the cell to detect phone numbers, dates/times etc. So I think I need to have the content in a UITextView within the UITableViewCell to make this possible.
How can I dynamically size the UITextView and add it to the cell with the content by modifying my code above? Sample code please with answers because I've already tried adding the UITextView as a subview of the cells contentView but it's not working as I'd expect.
you can use the sizeToFit or sizeThatFits: methods to resize the UITextView object
While creating cell, you need to add textView as its subView and no need to set textView size separately. You just need add margin values while returning height for row in
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
Related
I am using Autolayout and have a customised UITableViewCell that contains UITextView. The height of the cell and text view should be dynamically resized to accomodate larger contents.
Following answers from these links resize ui text view to its content and
dynamic ui text view, I have used a height constraint on the text view and set its value to the height of the content. This does the job of accommodating the textView, but it is overshooting the cell. I have tried options like adjusting the size of the cell also but none of them have helped. Surprisingly, sizeToFit seems to have no effect.
Here is the code I am using:
+ (SongAdditionalTextCell *)resize:(SongAdditionalTextCell *)additionalTextCell{
UITextView *textView = additionalTextCell.additionalText;
CGSize sizeThatFitsTextView = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
NSLog(#"content height is %f, frame height is %f", textView.contentSize.height, textView.frame.size.height );
additionalTextCell.addnlTextHeightConstraint.constant = sizeThatFitsTextView.height;
return additionalTextCell;
}
Please see the attached image of the view (text view is second cell). any suggestions appreciated?
I use this one:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 2)
{
NSString *cellText = #"init some text";
CGSize labelSize = [self calculateTextSize:cellText];
return labelSize.height + 20.0f;
}
return 45;
}
- (CGSize) calculateTextSize: (NSString*) text
{
UIFont *cellFont = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
CGFloat width = CGRectGetWidth(self.tableView.frame) - 40.0f;
CGSize constraintSize = CGSizeMake(width, MAXFLOAT);
CGRect labelRect = [cellText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cellFont} context:NSLineBreakByWordWrapping];
CGSize labelSize = labelRect.size;
return labelSize;
}
CGFloat width = CGRectGetWidth(self.tableView.frame) - 40.0f; -
Calculation of the maximum available width of the text, you can use self.view.frame or etc. - 40.0f - because i have indentation from the edge = 20.0f
Try this it working for me
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize labelSize = [[[Array objectAtIndex:indexPath.row] valueForKey:#"detail"] sizeWithFont:[UIFont boldSystemFontOfSize:10] constrainedToSize:CGSizeMake(255, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height +15;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpletableidentifier=#"simpletableidentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:simpletableidentifier];
if(cell == nil)
{
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpletableidentifier];
CGSize labelSize = [[[Array objectAtIndex:indexPath.row] valueForKey:#"detail"] sizeWithFont:[UIFont boldSystemFontOfSize:10] constrainedToSize:CGSizeMake(255, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
UILabel *desc=[[UILabel alloc]initWithFrame:CGRectMake(35,2,245,labelSize.height)];
desc.backgroundColor=[UIColor clearColor];
desc.tag=2;
desc.numberOfLines=0;
desc.lineBreakMode=NSLineBreakByWordWrapping;
desc.font=[UIFont boldSystemFontOfSize:10];
desc.textColor=[UIColor whiteColor];
[cell.contentView addSubview:desc];
}
NSString *Str3 = [[Array objectAtIndex:indexPath.row] valueForKey:#"detail"];
UILabel *desc=(UILabel *)[cell.contentView viewWithTag:2];
desc.text=Str3;
cell.selectionStyle=UITableViewCellSelectionStyleNone;
cell.backgroundColor=[UIColor clearColor];
cell.contentView.backgroundColor=[UIColor clearColor];
return cell;
}
Finally figured it out. #RoryMcKinnel's comment does help. Here's what I did in case it can help others. The problem was that I had two type of cells, one where I need to adjust the height (additionalText) and one where I do not need to do that.
In the raw version, I override both estmatedHeightForRowAtIndexPath and heightForRowAtIndexPath and in both methods if the index is for row which is additionalText, I send UITableViewAutomaticDimension else I send the frame height. Of course refinements can be done :) to send better values, but the core concept is same.
here is the code.
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.additionalTexts[#((long) indexPath.row)] != nil){
return UITableViewAutomaticDimension;
} else return [[SongTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainCellIdentifier].frame.size.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (self.additionalTexts[#((long) indexPath.row)] != nil){
return UITableViewAutomaticDimension;
} else return [[SongTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainCellIdentifier].frame.size.height;
}
and the resulting screen looks like
I have followed the instructions I have been able to find on stackoverflow to fix the following but none have worked. Below is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"DoCCell";
DoCCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[DoCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
CGSize constraintSize = CGSizeMake(cell.infoLabel.frame.size.width, MAXFLOAT);
CGSize labelSize = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = CGRectMake (cell.infoLabel.frame.origin.x, cell.infoLabel.frame.origin.y, labelSize.width, labelSize.height);
[cell.infoLabel setFrame:frame];
cell.infoLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.infoLabel.numberOfLines = 10;
_font = cell.infoLabel.font;
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize size = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 30.0;
}
but when I run my code the height of the cells is changed appropriately while the label size is not.
The cell is a custom cell and I have added the label via the .xib file. I tried manually stretching the label which worked in the sense that it would display all of the text so the issue is not in the wrapping of the label. I have also tested the cell.infoLabel.frame.size.height and the height value DOES change with the height of the cell as far as the value is concerned but it is not displayed as such. What am I doing wrong?
I think that the problem might be of adjusting the vertical alignment of the text in the UILabel instance.
I think you should do the following inside cellForRowAtIndexPath:
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.infoLabel.numberOfLines = 0;
[cell.infoLabel sizeToFit];
More details about it can be found in the following link: Vertical Alignment of UILabel Text
Hope this helps! :)
Use below code in cellForRowAtIndexPath delegate of tableView :
// getDynamicHeight function calculates height based on text length
//Dynamically determine height for cell text
CGFloat calculatedHeight = [self getDynamicHeight:#"Some very long text here"];
//Set name label frame based on text height
cell.infoLabel.frame = CGRectMake(cell.infoLabel.frame.origin.x,cell.infoLabel.frame.origin.y, cell.infoLabel.frame.size.width,calculatedHeight);
cell.infoLabel.numberOfLines = 5;
cell.infoLabel.text = #"Some very long text here";
// getDynamicHeight function
//Dynamically determine height for cell based in containing Text
-(CGFloat) getDynamicHeight : (NSString *) strCellTextName {
UILabel *lblGetDynamicHeight = [[UILabel alloc] init];
lblGetDynamicHeight.lineBreakMode = UILineBreakModeWordWrap;
lblGetDynamicHeight.text = strCellTextName;
CGSize labelStringSize = [lblGetDynamicHeight.text sizeWithFont:lblGetDynamicHeight.font constrainedToSize:CGSizeMake(142, 9999) lineBreakMode:lblGetDynamicHeight.lineBreakMode];
return labelStringSize.height; }
I'm using the following method implementation to calculate the height of a UITableViewCell which is containing multiline text:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
NSDictionary *fields = self.messageDetailsDictionary[#"fields"];
NSString *cellText = fields[#"message_detail"];
UIFont *cellFont = [UIFont systemFontOfSize:14.0];
CGSize constraintSize = CGSizeMake(250.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 20;
} else {
return tableView.rowHeight;
}
}
For completeness, here's the cellForRowAtIndexPath entry for this cell:
UITableViewCell *cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DetailCell"];
if (cell == nil) {
cell = [[UITableViewCell new] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"DetailCell"];
}
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.font = [UIFont systemFontOfSize:14.0];
NSDictionary *fields = self.messageDetailsDictionary[#"fields"];
cell.textLabel.numberOfLines = 0; // This means multiline
cell.textLabel.text = fields[#"message_detail"];
return cell;
The UITableViewCell is in a Grouped UITableView, that's important because it affects the width of the cell.
This is working to the extent that it does calculate a cell height that is large enough to accomodate the text being input, but it seems to be a little too large as there is a little too much space at the top and bottom of the cell. This is dependent on the quantity of text so I don't think it's related to the return labelSize.height + 20; statement. I suspect this is down to the '250.0f' value I'm using in CGSizeMake but I don't know what the correct value should be here.
Ultimately what I want is to have a cell that has consistent padding above and below the text for any content size.
Can anyone help?
Through a process of elimination it turns out that the magic number is 270.0f.
The width of the tableView frame can be obtained from self.tableView.frame.size.width. This is 320.0f and taking 50.0f from this (equals to 270.0f) seems to produce consistent results.
So the method should be as follows:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
NSDictionary *fields = self.messageDetailsDictionary[#"fields"];
NSString *cellText = fields[#"message_detail"];
UIFont *cellFont = [UIFont systemFontOfSize:14.0];
CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width - 50.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 20.0f;
} else {
return tableView.rowHeight;
}
}
I'm not exactly sure why 50.0f is the correct value, because I'm not sure how much of that 50.0f is the distance from the cell border to the tableView edge and how much of it is internal padding within the cell itself but it works unless you've amended either of those two values.
I am having a tableview with different heights for each cell based on the size of the text.
I calculate the rowsize in the delegate method -tableView:heightForRowAtIndexPath, and assign to the text in the datasource method -tableView:cellForRowAtIndexPath.
I am able to realize the appropriate height based on the text, but am not able to make the text wrap around; instead it just disappears off the screen. I am using a navigation-based app to generate the tableview in the child view controller using a nib. I played around with some of the options for tableview, but I can't make the text wrap. I would like to see the next wrap as if it were a textview, but I want the entire content displayed in the cell, without scroll bars in the table cell itself. Is this possible?
Here is the updated code, the height is adjusting itself correctly, but the cell is not word wrapping...
-
(CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *string = [self.quizDictionary objectForKey:[_temp objectAtIndex:testKV]];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height+25;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int row = indexPath.row;
if (row > 6) {
return nil;
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]
autorelease];
}
// configure the cell...
NSString *string = [self getQuestionPart];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
UITextView *textV=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height+10)];
textV.font = [UIFont systemFontOfSize:15.0];
textV.text=string;
textV.textColor=[UIColor blackColor];
// textV.editable=NO;
[cell.contentView addSubview:textV];
[textV release];
testKV++;
return cell;
}
You want:
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
to get your text to wrap within the cell. This in combination with a careful implementation of tableView:heightForRowAtIndexPath: should do the trick.
Yes it is possible!!!
Looking at this,you need to be somewhat tricky. You need to calculate the height of the textView dynamically and based on the Height of the TextView,you need to return the Height for the cell..
This is the code by which you can calculate the size of string....
First get the size of String & set the height of the cell based on string
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *label = [d valueForKey:#"Description"];
CGSize stringSize = [label sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height+25;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//}
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *string = [d valueForKey:#"Description"];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
UITextView *textV=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height+10)];
textV.font = [UIFont systemFontOfSize:15.0];
textV.text=string;
textV.textColor=[UIColor blackColor];
textV.editable=NO;
[cell.contentView addSubview:twitLbl];
[twitLbl release];
return cell;
}
This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.
It feels like it should be possible to get text to wrap without creating a custom cell, since a UITableViewCell contains a UILabel by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.
I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:
cell.text = #""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];
then I get a valid label, but setting numberOfLines on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the UILabel for the text to display - I'm just returning a large value for the height in heightForRowAtIndexPath.
Here is a simpler way, and it works for me:
Inside your cellForRowAtIndexPath: function. The first time you create your cell:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
}
You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.
The next part is to specify how large your UITableViewCell will be, so do that in your heightForRowAtIndexPath function:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = #"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
I added 20 to my returned cell height because I like a little buffer around my text.
Updated Tim Rupe's answer for iOS7:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = #"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.height + 20;
}
A brief comment / answer to record my experience when I had the same problem. Despite using the code examples, the table view cell height was adjusting, but the label inside the cell was still not adjusting correctly - solution was that I was loading my cell from a custom NIB file, which happens after the cell height in adjusted.
And I had my settings inside the NIB file to not wrap text, and only have 1 line for the label; the NIB file settings were overriding the settings I adjusted inside the code.
The lesson I took was to make sure to always bear in mind what the state of the objects are at each point in time - they might not have been created yet! ... hth someone down the line.
If we are to add only text in UITableView cell, we need only two delegates to work with (no need to add extra UILabels)
1) cellForRowAtIndexPath
2) heightForRowAtIndexPath
This solution worked for me:-
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:16];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
NSLog(#"%#",cell.textLabel.text);
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png" ]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize labelSize = CGSizeMake(200.0, 20.0);
NSString *strTemp = [mutArr objectAtIndex:indexPath.section];
if ([strTemp length] > 0)
labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];
return (labelSize.height + 10);
}
Here the string mutArr is a mutable array from which i am getting my data.
EDIT :- Here is the array which I took.
mutArr= [[NSMutableArray alloc] init];
[mutArr addObject:#"HEMAN"];
[mutArr addObject:#"SUPERMAN"];
[mutArr addObject:#"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:#"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:#"Where are BATMAN and SPIDERMAN"];
Now the tableviews can have self-sizing cells. Set the table view up as follows
tableView.estimatedRowHeight = 85.0 //use an appropriate estimate
tableView.rowHeight = UITableViewAutomaticDimension
Apple Reference
I use the following solutions.
The data is provided separately in a member:
-(NSString *)getHeaderData:(int)theSection {
...
return rowText;
}
The handling can be easily done in cellForRowAtIndexPath.
Define the cell / define the font and assign these values to the result "cell".
Note that the numberoflines is set to "0", which means take what is needed.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIFont *cellFont = [UIFont fontWithName:#"Verdana" size:12.0];
cell.textLabel.text= [self getRowData:indexPath.section];
cell.textLabel.font = cellFont;
cell.textLabel.numberOfLines=0;
return cell;
}
In heightForRowAtIndexPath, I calculate the heights of the wrapped text.
The boding size shall be related to the width of your cell. For iPad this shall be 1024.
For iPhone en iPod 320.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIFont *cellFont = [UIFont fontWithName:#"Verdana" size:12.0];
CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
return requiredSize.height;
}
I found this to be quite simple and straightForward :
[self.tableView setRowHeight:whatEvereight.0f];
for e.g. :
[self.tableView setRowHeight:80.0f];
This may or may not be the best / standard approach to do so, but it worked in my case.
Try my code in swift . This code will work for normal UILabels also.
extension UILabel {
func lblFunction() {
//You can pass here all UILabel properties like Font, colour etc....
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Now call simply like this
cell.textLabel.lblFunction()//Replace your label name
I think this is a better and shorter solution. Just format the UILabel (textLabel) of the cell to auto calculate for the height by specifying sizeToFit and everything should be fine.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = #"Whatever text you want to put here is ok";
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
[cell.textLabel sizeToFit];
return cell;
}
I don't think you can manipulate a base UITableViewCell's private UILabel to do this. You could add a new UILabel to the cell yourself and use numberOfLines with sizeToFit to size it appropriately. Something like:
UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];