Tableview cells not resizing properly to content - ios

For some strange reason the TableView Cells are not fitting the dynamic textual content properly. They should have a slight margin between the top and bottom of cell. Unfortunately, depending on the amount of textual content, some cells have no top and bottom margin(tightly packed) and others have huge margins.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
float result = 30;
if (indexPath.section != 0){
CGSize size = [[self textForIndexPath:indexPath isTitle:NO] sizeWithFont:kITDescriptionFont constrainedToSize:CGSizeMake(220, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
result = MAX(result, size.height);
}
return result;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *doubleCellIdentifier = #"ITDoubleDetailCEllIdentifier";
static NSString *cellIdentifier = #"ITDetailCEllIdentifier";
NSString *cellIdent = (indexPath.section == 0)? doubleCellIdentifier : cellIdentifier;
ITDescriptionCell *cell = (ITDescriptionCell *)[tableView dequeueReusableCellWithIdentifier:cellIdent];
if (!cell) {
UITableViewCellStyle style = (indexPath.section == 0)? UITableViewCellStyleValue2 : UITableViewCellStyleDefault;
cell = [[ITDescriptionCell alloc] initWithStyle:style reuseIdentifier:cellIdent];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell.textLabel setNumberOfLines:0];
[cell.textLabel setFont:kITDescriptionFont];
}
else {
[cell.textLabel setText:#""];
[cell.detailTextLabel setText:#""];
}
[cell sizeToFit];
return cell;
}

You need to dynamically calculate the height of your text and based on that and the padding you want, adjust the height of the cell through the following delegate method:
#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Subscription *sub = [_dictTask valueForKeyPath:#"subscription"];
NSArray *meta = sub.meta.allObjects;
NSString *text = [[meta objectAtIndex:indexPath.row] valueForKey:#"sum_value"];
CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];
return textSize.height + PADDING * 3;
}

Related

How to fix UITextView overflow when using autolayout in iOS8?

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

Dynamic height of UITableViewCell with storyboard

I have read alot about dynamic height for UITableViewCell and for the life of me I cannot get it working.
I have a uilabel with dynamic content within a dynamic cell.
I am using the storyboard and have the constraints as so :
I am populating the table using
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"labelCell";
detailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[detailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.dynamicLabel.text = sectionString;
return cell;
}
I do not know why everything I have tried has failed. I am thinking it may be the connections on the uiLabel?
This is it , Right :
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
NSString *text = myText;// [myArray objectAtIndex:indexPath.row];
CGSize size;
if (SYSTEM_VERSION_LESS_THAN(#"7.0")) {
// code here for iOS 5.0,6.0 and so on
CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:17]];
size = fontSize;
}
else {
// code here for iOS 7.0
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Helvetica Neue" size:19], NSFontAttributeName,
nil];
CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
size = fontSizeFor7.size;
}
NSLog(#"indexPAth %ld %f",(long)indexPath.section, size.height);
return size.height +30 ;
}
Finally, at the delegate of cellForRowAtIndexPath: don't forget to make the UILabel flexible for text :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ........
cell.dynamicLabel.text = sectionString;
cell.dynamicLabel.numberOfLines = 0;
return cell;
}

How to make UITableView row height respond to user's preferred text size (Dynamic Type)?

I would like the UITableView's row height to respond to changes in the user's preferred text size. For example, when the preferred text size increases, I would like to increase the row height by a proportional amount. Here's what I have so far:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
// observe when user changes preferred text size
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(preferredContentSizeChanged:) name:UIContentSizeCategoryDidChangeNotification object:nil];
}
- (void)preferredContentSizeChanged:(NSNotification *)notification
{
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
// leverage Text Kit's Dynamic Type
cell.textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
cell.textLabel.text = #"All work and no play...";
return cell;
}
So what's the best way to calculate a row height that reflects the user's preferred text size?
I have recently accomplished this and found it to be very simple. Instead of using sizeWithFont: you should use the new boundingRectWithSize:options:attributes:context method in iOS 7.
Set up your table view cell as usual and specify the preferredFontForTextStyle: on your text label as such:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier forIndexPath:indexPath];
//set your table view cell content here
[[cell textLabel] setText:#"Lorem ipsum dolour sit amet."];
[[cell textLabel] setNumberOfLines:0];
[[cell textLabel] setLineBreakMode:NSLineBreakByWordWrapping];
[[cell textLabel] setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
return cell;
}
Then to correctly determine the size of the text label, evaluate the boundingRectWithSize:options:attributes:context to calculate the required height.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//add your table view cell content here
NSString *string = #"Lorem ipsum dolor sit amet.";
NSDictionary *attributes = #{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleBody]};
CGRect frame = [string boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.bounds), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
return ceilf(CGRectGetHeight(frame);
}
You may want to subclass your table view cell also to listen for UIContentSizeCategoryDidChangeNotification notifications at which point you can update your UI when the user changes their preferences in Settings.app
- (void)contentSizeCategoryDidChangeNotificationHandler:(NSNotification *)notification
{
[[self textLabel] setFont:[UIFont preferredFontForTextStyle:UIFontTextStyleBody]];
}
Should you require additional padding around the text label, you can define a constant value such as
static CGFloat const TableViewCellPadding = 10.0;
With this in place, you can either add a constant value to the value returned from tableView:heightForRowAtIndexPath:
return (ceilf(CGRectGetHeight(frame) + TableViewCellPadding);
Or you could inset the frame returned from boundingRectWithSize:options:attributes:context as such:
CGRect frame = [string boundingRectWithSize:CGSizeMake(CGRectGetWidth(tableView.bounds), CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
frame = CGRectInset(frame, 0.0, TableViewCellPadding);
use this method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *fieldLabel = labelCell.textLabel.text;
CGSize textSize = [fieldLabel sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
float newHeight = textSize.height+22.0f;
return newHeight;
}
Add below code to cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
UILabel *lblfield=[[UILabel alloc] init];
NSString *fieldLabel=[NSString stringWithFormat:#"%#",labelCell.textLabel.text];
CGSize textSize = [fieldLabel sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-20, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
float newHeight = textSize.height+22.0f;
lblfield.frame=CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width, newHeight);
lblfield.backgroundColor=[UIColor clearColor];
lblfield.text=strusername;
[cell addSubview:lblfield];
return cell;
}

How to increase the label and cell size on clicking a button in a TableViewCell.

I want to expand the cell size after clicking a seeMoreBtn on cell.
The label and cells have varying length, but their is a constraint in size of label.
When a status is too big, I added a seeMoreBtn, after clicking on see more the remaining text will be shown below, then how to increase the label and cell size.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(300.0f, 150.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:constraint lineBreakMode:NSLineBreakByCharWrapping];
CGFloat height1 = MAX(size.height, 44.0f);
return height1 + (40.0f);
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell-%d",indexPath.row];
cell=[tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
int lbltag = 1000;
label=[[UILabel alloc]initWithFrame:CGRectZero];
[label setLineBreakMode:NSLineBreakByWordWrapping];
[label setMinimumScaleFactor:14.0f];
[label setNumberOfLines:0];
[label setFont:[UIFont systemFontOfSize:14.0f]];
NSString *text = [items objectAtIndex:[indexPath row]];
[label setText:text];
label.tag = lbltag;
[cell addSubview:label];
CGSize constraint1=CGSizeMake(300.0f, 150.0f);
CGSize size1=[text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
[label setFrame:CGRectMake(10.0f, 10.0f, 300.0f, MAX(size1.height, 44.0f))];
int countText=text.length;
if (countText>=350) {
seeMoreBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[seeMoreBtn setTitle:#"See More" forState:UIControlStateNormal];
seeMoreBtn.frame=CGRectMake(220.0f, MAX(size1.height, 44.0f)-10, 80.0f, 20.0f);
seeMoreBtn.tag=indexPath.row ;
[seeMoreBtn addTarget:self action:#selector(increaseSize:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:seeMoreBtn];
}
return cell;
}
-(void)increaseSize:(UIButton *)sender{
//What to write here that can adjust the label and cell size
}
It would be better, if you subclass the UITableViewCell and use the layoutSubviews to adjust when you adjust the size of the cell.
//In SMTableViewCell.h
#interface SMTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *statusLabel;
#property (weak, nonatomic) IBOutlet UIButton *seeMoreButton;
//SMTableViewCell.m
- (void)layoutSubviews
{
CGRect labelFrame = self.statusLabel.frame;
labelFrame.size.height = self.frame.size.height - 55.0f;
self.statusLabel.frame = labelFrame;
CGRect buttonFrame = self.seeMoreButton.frame;
buttonFrame.origin.y = labelFrame.origin.y+labelFrame.size.height+10.0f;
self.seeMoreButton.frame = buttonFrame;
}
Keep an array to store the selectedIndexPaths:
#property (nonatomic, strong) NSMutableArray *selectedIndexPaths;
Calculate the height of the cell:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
BOOL isSelected = [self.selectedIndexPaths containsObject:indexPath];
CGFloat maxHeight = MAXFLOAT;
CGFloat minHeight = 40.0f;
CGFloat constrainHeight = isSelected?maxHeight:minHeight;
CGFloat constrainWidth = tableView.frame.size.width - 20.0f;
NSString *text = self.items[indexPath.row];
CGSize constrainSize = CGSizeMake(constrainWidth, constrainHeight);
CGSize labelSize = [text sizeWithFont:[UIFont systemFontOfSize:15.0f]
constrainedToSize:constrainSize
lineBreakMode:NSLineBreakByCharWrapping];
return MAX(labelSize.height+75, 100.0f);
}
Initialize custom Show more TableViewCell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellIdentifier";
SMTableViewCell *cell= (SMTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([SMTableViewCell class])
owner:nil
options:nil] lastObject];
}
BOOL isSelected = [self.selectedIndexPaths containsObject:indexPath];
cell.statusLabel.numberOfLines = isSelected?0:2;
NSString *text = self.items[indexPath.row];
cell.statusLabel.text = text;
NSString *buttonTitle = isSelected?#"See Less":#"See More";
[cell.seeMoreButton setTitle:buttonTitle forState:UIControlStateNormal];
[cell.seeMoreButton addTarget:self action:#selector(seeMoreButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[cell.seeMoreButton setTag:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Button click event method:
- (void)seeMoreButtonPressed:(UIButton *)button
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
[self addOrRemoveSelectedIndexPath:indexPath];
}
- (void)addOrRemoveSelectedIndexPath:(NSIndexPath *)indexPath
{
if (!self.selectedIndexPaths) {
self.selectedIndexPaths = [NSMutableArray new];
}
BOOL containsIndexPath = [self.selectedIndexPaths containsObject:indexPath];
if (containsIndexPath) {
[self.selectedIndexPaths removeObject:indexPath];
}else{
[self.selectedIndexPaths addObject:indexPath];
}
[self.tableView reloadRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
Same Event is given if the cell is selected:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self addOrRemoveSelectedIndexPath:indexPath];
}
Sample Demo project link.
Add a property like:
#property(strong, nonatomic) NSArray *enlargedIndexPaths;
Initialize it to an empty array. Implement the table view delegate:
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return ([self.enlargedIndexPaths containsObject:indexPath])? 88.0 : 44.0;
}
Then in increaseSize:
UITableViewCell *cell = sender.superview;
NSIndexPath *indexPath = [self.tableView indexPathFoCell:cell];
[self.enlargedIndexPaths addObject:indexPath];
// do you want to enlarge more than one at a time? You can remove index paths
// here, too. Just reload them below
[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:self.enlargedIndexPaths] withRowAnimation:UITableViewRowAnimationTop];
[self.tableView endUpdates];
Well, the idea is to change the cells height, based on a value you set for the cell.
You can have an NSArray, where you just mark for all cells a value: isExpanded (true or false).
To recap, create an NSMutableArray that will store the cell state (expanded or not):
NSMutableArray *cellState;
init the array and fill it with zeros for all your UITableView items Array.
When the cell is expanded, set the cellState objectAtIndex value from 0 to 1 (marking it as expanded).
Then reload that cell:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationFade];
and modify the - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; function to return a bigger value if the cell is expanded...
That's it!

UITableViewCell wrap text in UINavigationController app

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;
}

Resources