iOS - UITableViewCell text alignment - ios

I've added a tableView and dragged a table view cell into it.
in the utilities panel, I changed the style to subtitle.
I've also tried changing it in code:
- (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];
}
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.text = [myArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [myArray2 objectAtIndex:indexPath.row];
return cell;
The center alignment doesn't work!
I've tried adding a label object to the cell to have a workaround. But I don't know how to access it. even though I assigned an outlet to it, this wouldn't work:
cell.labelForCell....
What should I do?
any suggestions on how I make it work the usual way, without adding a label to the cell or something?

For the UITableViewCellStyleSubtitle text alignment cannot be changed
You will have to put a label and add your alignment to it,
To do that you could use this code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *myLabel;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
myLabel = [[UILabel alloc] initWithFrame:Your_Frame];
//Add a tag to it in order to find it later
myLabel.tag = 111;
//Align it
myLabel.textAlignment= UITextAlignmentCenter;
[cell.contentView addSubview:myLabel];
}
myLabel = (UILabel*)[cell.contentView viewWithTag:111];
//Add text to it
myLabel.text = [myArray objectAtIndex:indexPath.row];
return cell;
}

The problem with the subtitle style is that it does a [self.textLabel sizeToFit] when it lays out. When you center in a container that is the perfect size of the contents, nothing changes.
Try this. In a subclass of UITableViewCell, set your textAlignment, and use this as your layoutSubviews code:
- (void)layoutSubviews
{
[super layoutSubviews];
{
CGRect frame = self.textLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);
frame.origin.x = 0.0;
self.textLabel.frame = frame;
}
{
CGRect frame = self.detailTextLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);
frame.origin.x = 0.0;
self.detailTextLabel.frame = frame;
}
}
This makes the textLabel's frame full width, and thus allows the centering effect to be noticeable.
Note: since this overrides layoutSubviews, there is a performance cost as it will be called often.

I think the reason is that: the textLabel's width depends on the text length, if the text is too long to show all in a signal line, and you have already set the line break mode and set the number of lines to 0, you will find that the text alignment will be work.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (nil == cell)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease];
cell.textLabel.textAlignment = UITextAlignmentLeft;
cell.textLabel.textColor = [UIColor redColor];
cell.detailTextLabel.textColor = [UIColor greenColor];
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation;
cell.textLabel.numberOfLines = 0;
}
cell.textLabel.text = [NSString stringWithFormat:#"You can initialize a very long string for the textLabel, or you can set the font to be a large number to make sure that the text cann't be shown in a singal line totally:%d", indexPath.row];
return cell;
}

I think adjusting the frame will work. I had style of UITableViewCellStyleValue2 but If i have a bit lengthy text in textLabel, it getting truncated at tail and textAlignment does not work here, so thought of increase the width textLabel.
-(void)layoutSubviews{
[super layoutSubviews];
if ([self.reuseIdentifier isEqualToString:#"FooterCell"]) {
CGRect aTframe = self.textLabel.frame;
aTframe.size.width += 40;
self.textLabel.frame = aTframe;
CGRect adTframe = self.detailTextLabel.frame;
adTframe.origin.x += 70;
self.detailTextLabel.frame = adTframe;
}
}

It is impossible to change frame for textLabel and detailTextLabel in UITableViewCell
right in cellForRowAtIndexPath: method.
If you don't want to subclass your cell you can implement a small hack using
performSelector:withObject:afterDelay:
with zero delay for changing geometry right after default layoutSubviews:
[self performSelector:#selector(alignText:) withObject:cell afterDelay:0.0];
See details at here

Hi please add the following instead of your code,
cell.textLabel.textAlignment = UITextAlignmentCenter;
cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
change to
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.detailTextLabel.textAlignment = NSTextAlignmentCenter;
it will work fine.

Related

UITextView doesn't display in multiple lines

I have a UITableViewCell that has a UITextView. When the table loads all of the text in each UITextView appears in a single line. I created the UITextView in IB with a white text color. How do I get it to display in multiple lines, and why did the text color switch to black?
The height of each UITableViewCell is correct. It used to display the text in multiple lines after I refreshed the table by pulling down, but for some reason that stopped working too.
If there's any other information you require, please let me know.
Here's the relevant code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
BIDChatCell *cell = (BIDChatCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[BIDChatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell
cell.backgroundColor = [UIColor clearColor];
cell.userLabel.text = [object objectForKey:#"username"];
NSString *time = [object objectForKey:#"time"];
NSString *date = [time substringToIndex:10];
cell.timeLabel.text = date;
NSString *chatText = [object objectForKey:#"text"];
UIFont *font = [UIFont systemFontOfSize:14];
CGSize size = [chatText sizeWithFont:font constrainedToSize:CGSizeMake(200.0f, 1000.0f) lineBreakMode:UILineBreakModeCharacterWrap];
cell.textStringView.frame = CGRectMake(75, 15, size.width +20, size.height + 20);
cell.textStringView.font = [UIFont fontWithName:#"Helvetica" size:14.0];
cell.textStringView.text = chatText;
[cell.textStringView sizeToFit];
[cell.textStringView.textContainer setSize:cell.textStringView.frame.size];
CGRect frame = cell.textStringView.frame;
frame.size.height = cell.textStringView.contentSize.height;
cell.textStringView.frame = frame;
[cell layoutSubviews];
return cell;
}
Here's an image:
Try setting the height of the textView like so:
CGRect frame = cell.textStringView.frame;
frame.size.height = cell.textStringView.contentSize.height;
cell.textStringView.frame = frame;
Does the UITextView have the proper autoresizingMask?
It likely needs it set to (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight) to allow the textview to grow (as it normally uses a UIScrollView instead)

UITableViewCell to display long texts in cell.textLabel

If I have a long text I have to increase the cell size to fit the text.
When I assign: cell.textLabel.text = #"my string" , if the string is long it gets truncated.
How can I display the text in two or more rows for this case? I am using UITableViewCell only and not subclassing it anywhere. Is there some code to display long texts using cell.textLabel directly? I am not talking about adding a seperate view to cell.
cell.textLabel will not allow you to line break a string into two lines. What you will have to do is customize it add your own UILabel to UITableViewCell and define its parameters.
Here's a working code that you can add to your TableView.
//define labelValue1 in your .h file
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//NSLog(#"Inside cellForRowAtIndexPath");
static NSString *CellIdentifier = #"Cell";
// Try to retrieve from the table view a now-unused cell with the given identifier.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// If no cell is available, create a new one using the given identifier.
if (cell == nil)
{
// Use the default cell style.
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
labelValue1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; //adjust label size and position as needed
labelValue1.font = [UIFont fontWithName:#"BradleyHandITCTT-Bold" size: 23.0];
labelValue1.textColor = [UIColor whiteColor];
labelValue1.textAlignment = NSTextAlignmentCenter;
labelValue1.numberOfLines = 2; //note: I said number of lines need to be 2
labelValue1.backgroundColor = [UIColor clearColor];
labelValue1.adjustsFontSizeToFitWidth = YES;
labelValue1.tag = 100;
[cell.contentView addSubview:labelValue1];
}
else
{
labelValue1 = (UILabel *) [cell viewWithTag:100];
}
// Set up the cell.
NSString *str1 = [arryData3 objectAtIndex:indexPath.row];
labelValue1.text = str1;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Multiple lines can be shown using
cell.textLabel.LineBreakMode = NSLineBreakByWordWrapping
This is for Swift.
cell.textLabel?.numberOfLines = 10 /// or the number you like.

Table View troubles with dequeue cell

So I am having trouble showing my data in a UITableView. I do believe it has something to do with reusing the cells. I have checked online and here at SO but have not found a solution that works for me. Any help would be appreciated.
I have an Array that is populated by text and pictures. I am then showing the information in a tableView. If I were to use static sized cells everything works out fine, but the amount of text changes, so I have also implemented the heightForRowAtIndexPath method. This works as well, until I scroll all the way down to the bottom.
After that, when I scroll back up, all the cell heights change and the display gets all jumbled. Some text gets cut off, pictures get chopped and some of the cells only have the last portion of text. I really think it has something to do with reusing the cells, but I don’t know how to attack this problem. Below is my code for cellForRowAtIndexPath and heightForRowAtIndexPath.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]])
{
NSString *label = [_theBigArray objectAtIndex:indexPath.row];
CGSize stringSize = [label sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UITextView *textV = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height +50)];
textV.font = [UIFont systemFontOfSize:15];
textV.text = [_theBigArray objectAtIndex:indexPath.row];
textV.textColor = [UIColor blackColor];
textV.editable = NO;
[cell.contentView addSubview:textV];
}
else if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]])
{
UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 290, 100)];
imageV.contentMode = UIViewContentModeScaleAspectFit;
imageV.image = [_theBigArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:imageV];
}
return cell;
[tableView reloadData];
}
For heightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
int rowHeight = 0.0f;
if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]])
{
NSString *temp = [_theBigArray objectAtIndex:indexPath.row];
CGSize size = [temp sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:NSLineBreakByWordWrapping];
rowHeight = size.height+50;
}
else if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]])
{
rowHeight = 115.0f;
}
//NSLog(#"rowHeight is %i", rowHeight);
return rowHeight;
[tableView reloadData];
}
I even tried to make two different cells and call them separately, but the same thing happens. I did still use the same heightForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *newCell = [[UITableViewCell alloc] init];
if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[NSString class]])
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
NSString *label = [_theBigArray objectAtIndex:indexPath.row];
CGSize stringSize = [label sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:NSLineBreakByWordWrapping];
UITextView *textV = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height +50)];
textV.font = [UIFont systemFontOfSize:15];
textV.text = [_theBigArray objectAtIndex:indexPath.row];
textV.textColor = [UIColor blackColor];
textV.editable = NO;
[cell.contentView addSubview:textV];
newCell = cell;
}
else if ([[_theBigArray objectAtIndex:indexPath.row] isKindOfClass:[UIImage class]])
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"PictureCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"PictureCell"];
}
UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 290, 100)];
imageV.contentMode = UIViewContentModeScaleAspectFit;
imageV.image = [_theBigArray objectAtIndex:indexPath.row];
[cell.contentView addSubview:imageV];
newCell = cell;
}
return newCell;
[tableView reloadData];
}
Any ideas?
The main problem is that you're adding subviews to cells every time they scroll in, but when a cell is reused, it will already have those subviews added. (That is, when a cell is reused, it will already have a UITextView or UIImageView depending on the reuse identifier.)
You need to check if these subviews exist first; this is commonly done by using the -[UIView viewWithTag] method, or by subclassing UITableViewCell and assigning each view as a property.
(You can take a look at the SO question How to get other control value from UITableViewCell? to see how to use viewWithTag. I would avoid subclassing UITableViewCell until you're more comfortable with the out-of-the-box implementation.)
Also, this line of code:
UITableViewCell *newCell = [[UITableViewCell alloc] init];
is a terrible idea, because you are creating a new UITableViewCell without checking to see if you can reuse one first. This defeats the entire purpose of reusing cells, which is fast scrolling performance. Instead, just declare it without initializing it:
UITableViewCell *newCell;
Also, in heightForRowAtIndexPath, you are
declaring rowHeight as an int (it should be a CGFloat)
trying to call reloadData after the method returns (which will never happen, but you should never try to call reloadData from this method)

UILabel height inside UITableViewCell

I'm trying to create a tableview where the height of the cells are dynamic.
So far I manage to set the height of the cells depending on the custom UILabel I've added inside.
With the regular cell.textLabel it works fine, but when I use my own label something goes wrong. I only see half the label, but when I scroll up and down, sometimes the label extends and shows all the text... You can see where the label should end in the image.
Image
This is the text inside the cellForRowAtIndexPath:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel = (UILabel *)[cell viewWithTag:100];
nameLabel.numberOfLines = 0;
nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];
[nameLabel setBackgroundColor:[UIColor greenColor]];
return cell;
Unless you have typos in the code you posted, you don't seem to be adding the label to the cell at all. You also seem to be creating a new label every time, and then replacing the contents of your nameLabel pointer with the cell's view (which will always be nil).
Try doing something like this first and then see how it looks:
static NSString *CellIdentifier = #"Cell";
UILabel *nameLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
nameLabel = [[UILabel alloc] init];
nameLabel.tag = 100;
nameLabel.numberOfLines = 0;
[nameLabel setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:nameLabel];
}
else {
nameLabel = (UILabel *)[cell viewWithTag:100];
}
// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];
nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];
return cell;
You will also need to tell the tableView what size each cell needs to be using the tableView:heightForRowAtIndexPath: delegate method. That will mean getting the relevant Car object again and calculating the height using sizeWithFont:sizeWithFont:forWidth:lineBreakMode:
How are you setting the height of the cell? It should be done in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
You should calculate and return the height of the UITableViewCell in the following method:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
Here you should do your initial calculation of how high your cell should be.
For example:
CGSize textSize = [myString sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(320, 9999)];
return textSize.height;

How do I wrap text in a UITableViewCell without a custom 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];

Resources