I have created a UITableViewCell with a NIB file.
There is 1 label in it which is going to contain a tweet. So it needs to be a dynamic height. There also is a timeAgo label that has to fit underneath the tweet label.
I'm trying stuff with frames en sizes but I can't get the perfect solution..
I do this in the UITableViewCell file in the drawrect method.
self.tweet.lineBreakMode = UILineBreakModeWordWrap;
self.tweet.numberOfLines = 0;
self.tweet.font = [UIFont fontWithName:#"Arial" size:13.0f];
[self.tweet sizeToFit];
CGFloat tweetHeight = self.tweet.frame.size.height;
self.timeAgo.lineBreakMode = UILineBreakModeWordWrap;
self.timeAgo.numberOfLines = 0;
self.timeAgo.font = [UIFont fontWithName:#"Arial" size:11.0f];
[self.timeAgo sizeToFit];
CGFloat timeAgoHeight = self.timeAgo.frame.size.height;
self.timeAgo.frame = CGRectMake(88, tweetHeight, 100, timeAgoHeight + 10.0f);
I have also tried a stringhelper which I found in a tutorial.
The:
- (CGFloat)RAD_textHeightForSystemFontOfSize:(CGFloat)size {
My HeightForRow methods is also already different because I use different cell styles.
At the moment I return a hard value for each cell style but that also needs to change to the cellheight.
See this tutorial, http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/
The trick is to make the label grow with the size of the cell, than you can just set the size of the cell and the cell will grow with it.
Set the timeAgo label to align it self to the bottom of the cell.
Set the numberOfLines of tweet to 0 via IB,re move all the draw code and only implement the following:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id item = [self.item objectAtIndex:indexpath.row];
CGFloat height = 85.0f;
if ([item isKindOfClass:[Tweet class]]) {
Tweet *tweet = (Tweet *)item;
CGSize titleSize = [tweet.tweet sizeWithFont:[UIFont fontWithName:#"Arial" size:13.0f] constrainedToSize:CGSizeMake(260.0f, MAXFLOAT)];
// adde the 24 pixels to get the height plus the time ago label.
height = titleSize.height + 24.0f;
} else if( [item isKinfOfClass:[SC_Release class]]) {
height = 65.0f;
}
return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [tweetsArray indexPath.row];
CGSize labelSize = [string sizeWithFont:[UIFont fontWithName:#"Verdana" size:17.0]
constrainedToSize:CGSizeMake(280.0f, MAXFLOAT)
lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
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 have an application in which I am loading a UITableView from 3 types custom cells. I made 3 custom classes for that and added all the elements Programmatic by using layout subview method. But the issue is all the 3 has a text view in it. it can be variable. after that text view content I need to add a button and a label. That I can do, but how to increase the size of the cell according to the content view size?
Please check the custom cell height will be the same as table view each cell height.
You can use following function to adjust table view's cell height.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return height;
}
You can use code like this.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Defination *definition = [self.dataSource objectAtIndex:indexPath.row];
NSString *detailString = definition.detailString;
CGSize detailSize;
detailSize = [detailString sizeWithFont:fontSize(12.0) constrainedToSize:CGSizeMake(420, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
return detailSize.height + 20.0;
}
ill add another example of measuring a more complex cell.
mind my measurement code isnt 100% correct but it shows the approach
+ (CGFloat)calculatedCellHeightForTweet:(id)tweet width:(CGFloat)width {
//text
CGSize s1 = [tweet[#"text"] sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
//user
NSString *text;
if(![tweet[#"to_user"] isKindOfClass:[NSNull class]])
text = [NSString stringWithFormat:#"%# > %#", tweet[#"from_user"], tweet[#"to_user"]];
else
text = tweet[#"from_user"];
CGSize s2 = [text sizeWithFont:[UIFont boldSystemFontOfSize:[UIFont labelFontSize]]
forWidth:width
lineBreakMode:NSLineBreakByWordWrapping];
return fmaxf(s1.height + s2.height + /*padding*/ 44, 60);
}
you can calculate height by using below function
-(CGSize)SizeOfString:(NSString *)string withFont:(UIFont *)font constrainedToWidth:(CGFloat)width
{
CGSize size = [string sizeWithFont:font constrainedToSize:CGSizeMake(width, 4000) lineBreakMode:UILineBreakModeWordWrap];
return CGSizeMake(width, size.height + 10);
}
Call
CGSize size = [self SizeOfString:your_text withFont:your_font constrainedToWidth:width_of_showing_area];
I need to resize the cell height based on the content size/length.tried several methods, which one gives the exact height without overlapping?
see this tutorial for change UITableViewCell Height Dynamically..
Resizing-A-UITableViewCell
and also use this tutorial..
uitableviewcell-dynamic-height
also use tableView:heightForRowAtIndexPath: method for set height of cell with indexpath
This is from my previous answer - Customizing UITableViewCell's height:
Use this method to get the text height of the text
-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{
CGSize maximumSize = CGSizeMake(labelWidth, 10000);
//provide appropriate font and font size
CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:#"Trebuchet MS" size:13.0f]
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeTailTruncation];
return labelHeighSize.height;
}
This method will return the height of the text you are passing. Add this method in your class. And use the tableView:heightForRowAtIndexPath: delegate method to set the height for each cell
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Feedback *item = [self.items objectAtIndex:indexPath.row];
CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here
return textHeight;
}
Sample you can edit and try
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *itemAtIndex = (NSDictionary *)[chatQuestions objectAtIndex:indexPath.row];
if ([self sizeForText:[itemAtIndex objectForKey:#"text"]].height+20>50) {
return [self sizeForText:[itemAtIndex objectForKey:#"text"]].height+20;
}
else{
return 50;}
}
-(CGSize)sizeForText:(NSString*)text
{
CGSize constraintSize;
constraintSize.width = 190.0f;
constraintSize.height = MAXFLOAT;
UIFont *labelFont = [UIFont fontWithName:#"Noteworthy-Light" size:18];
CGSize stringSize =[text sizeWithFont:labelFont constrainedToSize: constraintSize lineBreakMode: UILineBreakModeWordWrap];
return stringSize;
}
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
In your case you need to set the height of cell based on the label.
Check the link :
http://dcraziee.wordpress.com/2013/05/22/calculate-size-of-uillabel-base-on-text-in/
There is a function named
-(CGFloat)getHeightForLabel:(NSString *)_str font:(UIFont *)fontOfObject
Use that function to calculate height as :
-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat _height = [self getHeightForLabel:self.label.text font:[self.label font]];
return _height;
}
I am using UITableView with header in my app and I want to add string in the cell of tableview. In the cell below the header I want to fill string data and as per the size of the string I want to increase the height of the cell
for better understanding I attach the file.
I have check the link1,link2 and link3
but I am not able to get answer which I want.
for better understanding I attach the image too.
label Instructions indicates my header and in next cell I want to add string.
then How can I increase the height of cell according to string length.
thanx in advance.
Implement the method
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//return appropriate value based on IndexPath.row
UIFont *font = textLabel.font; // use custom label's font
NSString *myText = #"your text for row at index path";
CGSize size = [myText sizeWithFont:font forWidth:textLabel.frame.size.width lineBreakMode:UILineBreakModeWordWrap];
return (size.height+20); //10 pixels space above the textlabel and below 10 pixels space
}
as mentioned in the link you have referred.
Use the following delegate method:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//return appropriate value based on IndexPath.row
}
Within this Method, from the datasource aray, check the length of the string for tht particular row and return the height accordingly.
Try this code for cell size.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text =#"your String";
CGSize constraint = CGSizeMake(CellContentWidth - (CellMargin * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (cellMargin* 2);
}
This code use for cell label Height.
NSString *text = [arr objectAtIndex:indexPath.row];
CGSize constraint = CGSizeMake(labelwidth , 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
cell.lbl3.frame=CGRectMake(X,Y ,W, height);
Is there a way to adjust the size of a table view AND get the text to wrap in iPhone? I'm using the following code, and it succeeds in adjusting the height of the cell, but the text doesn't wrap, it just ends with "...."
- (CGFloat)tableView:(UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
CGSize cellHeight;
City *thisCity = [cities objectAtIndex:indexPath.row];
NSString * myString = thisCity.cityName;
cellHeight = [myString sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300.0, 1000.0) lineBreakMode:UILineBreakModeWordWrap];
return cellHeight.height + 20;
}
There are two things here:
Wrapping of text in the displayed label - to do this you have to define for your UILabel how it looks as a container - how many rows can it have, does it wrap and of course how big it is. You can do this either in code or in the Interface Builder (depending on if you are using your own custom cell)
You can change your UITableView's width either in the Interface Builder or in code (myTableView.frame = CGRectMake(x,y,width,height))
BUT notice the if you are using a UITableViewController as your view controller - you CANNOT adjust the width of the table view
Found the perfect answer at
How do I wrap text in a UITableViewCell without a custom cell
Here's the code
- (UITableViewCell *)tableView:(UITableView *)tv
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =
[ tv dequeueReusableCellWithIdentifier:#"cell"];
if( nil == cell ) {
// this sets up a resusable table cell
cell = [ [[UITableViewCell alloc]
initWithFrame:CGRectZero reuseIdentifier:#"cell"] autorelease];
// support line break mode
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
// 0 means any number of lines
cell.textLabel.numberOfLines = 0;
// set it up with a consistent font with the height calculation (see below)
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
}
// set the name of the city
if (indexPath.row < cities.count ) {
City *thisCity = [cities objectAtIndex:indexPath.row];
cell.textLabel.text = thisCity.cityName;
}
else
{
cell.textLabel.text = #"Add New City...";
cell.textLabel.textColor = [UIColor lightGrayColor];
cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
// get the height of the row
- (CGFloat)tableView:(UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
City *thisCity = [cities objectAtIndex:indexPath.row];
NSString * cellText = thisCity.cityName;
// set a font size
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
// get a constraint size - not sure how it works
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
// calculate a label size - takes parameters including the font, a constraint and a specification for line mode
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
// give it a little extra height
return labelSize.height + 20;
}
Assign your String in a UILabel.and use this Thread to do. other wise Assign the string to a UItextView and hidden it.you can use
textview.contentSize.height//use this to your cell hieght