IPhone Issues with autosizing cell based on text input - iphone

I'm using the below code to try and automatically space out my cell height to the amount of text in the cell. At the moment it works but adds whitespace to the top and the bottom of the cell (say if theres 10 lines, theres 4 lines before and after, but if it's 200 lines theres 40 lines above and below (as in the screenshot) so it's becoming a bit of a pain!)
- (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];
}
AssessObject *newObj1;
newObj1=[totalArray objectAtIndex:indexPath.section];
cell.textLabel.text = newObj1.routeImage;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
AssessObject *newObj1;
newObj1=[totalArray objectAtIndex:indexPath.section];
NSString *cellText = newObj1.routeImage;
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:16.0];
CGSize constraintSize = CGSizeMake(190.0, CGFLOAT_MAX);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height;
}

Well, it looks like you're using two different font sizes when calculating your height and on the actual label. That is very likely to blame for the extra space.
EDIT:
Taking another look, the width you're using when calculating the size is only 190. From the screenshots you supplied, it looks like your label is quite a bit wider than that. Make sure the dimensions, font sizes, and line break modes you're using in the actual label are correctly mirrored when calculating the size. My initial answer is probably not correct, since you're using a larger size in the actual label than the one you're calculating with.

Related

can i give space between two cells in tableview in ipohne?

static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSLog(#"%d",indexId);
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
///////////////////// Cell Title /////////////////////
//cell.textLabel.font = [UIFont fontWithName:#"Noteworthy" size:20.0];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
cell.textLabel.highlightedTextColor = [UIColor orangeColor];
}
///////////////////// Cell Title /////////////////////
cell.textLabel.text = [NSString stringWithFormat:#" %#", [test.arrTitle objectAtIndex:indexPath.row]];
the above code where i need change code for get sapce between tableview cell label
thanks and regards
There's a few ways to add space between cells in a table view.
You can adjust the height of the table view cells in Interface Builder, you can do custom cells with different heights, or you can programatically return different heights via the tableView:heightForRowAtIndexPath: delegate method.
A easy way to add space between two cells would be to use the sections to display the data. Make sure that each section contains just one cell. Then, you can add sectionHeaderView or sectionFooterView between subsequent sections to make it right.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [myItems count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 1;
}
#define customSeparatorHeight 3
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
return [UIView alloc] initWithFrame:CGRectMake(0,0, tableView.bounds.size.width, customSeparatorHeight)];
}

How to scroll UI tableview vertically and horizontally?

i have table view in my app and each row have long text so its possible to scroll whole table so user can read entire text
also i am using following code to set up my cell
-
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//buttonCount=0;
static NSString *CellIdentifier = #"Cell";
static NSUInteger const kLeftLabel = 100;
static NSUInteger const kRightLabel = 101;
row = [indexPath row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
CGRect leftFrame = CGRectMake(2, 5, 45, 30);
CGRect rightFrame = CGRectMake(50, 5, 400, 30);
left = [[[UILabel alloc]initWithFrame:leftFrame]autorelease];
left.tag = kLeftLabel;
left.font = [UIFont systemFontOfSize:13];
[cell.contentView addSubview:left];
right = [[[UILabel alloc]initWithFrame:rightFrame]autorelease];
right.tag=kRightLabel;
right.font = [UIFont systemFontOfSize:13];
[cell.contentView addSubview:right];
}
else {
left = (UILabel*)[cell.contentView viewWithTag:kLeftLabel];
right=(UILabel*)[cell.contentView viewWithTag:kRightLabel];
}
left.text =[secondSplitArrayValue objectAtIndex:row];
right.text=[splitArrayValue objectAtIndex:row];
if (indexPath.row == 0)
{
[cell setSelectionStyle:UITableViewCellSelectionStyleNone ];
}
return cell;
}
by use of above code i have two column so 1st column have small text but 2nd is very much big and to read i want to scroll it horizotally.
i hope some one will solve this problem.
thank you in advance
To solve your problem there is no need to modify scrolling of table view you can do it by following code... by using this code you can show ur text in multiline in the default label of table view cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyCell";
UITableViewCell *cell =(UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = #"Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. Its for testing. ";
return cell;
}
You need to use the multiline label for the long text and set the height of your long cell properly by calculating with long text in below function.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
for more you can read the tutorial
place your UITableView in UIScrollview
But looking at your case there is no need to do such thing, I would prefer to make the cells height Dynamic according to the Text.
Just use above code which might help to solve your problem:
You need to use Custom Cell having TextView in cell;
//Calculate the Height & Width of Text
CGSize stringSize = [#"Your sample text whose height & Width need to be calulated" sizeWithFont:[UIFont boldSystemFontOfSize:[YurTextField font] constrainedToSize:CGSizeMake(230, 9999) lineBreakMode:UILineBreakModeWordWrap];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyCell";
UITableViewCell *cell =(UITableViewCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
[Over here take TextView calculating the Height & width of String ];
// [add TextView it cells contentView];
[cell.contentView addSubview:TextView];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
CGSize stringSize = [#"Your sample text whose height & Width need to be calulated" sizeWithFont:[UIFont boldSystemFontOfSize:[YurTextField font] constrainedToSize:CGSizeMake(230, 9999) lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height;
}
if it doesn't solve your purpose then try using below alternative
Although I can suggest you to use the ScrollView & set it Delegate.
Add your UITAbleView as SubView to ScrollView & keep the size of scrollview according to the view how much you want to Scroll.
->View
-->ScrollView
--->UITableView

iPhone - adjust size of table view according to text

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

Wrap words in uitableview, iphone [duplicate]

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

How can I create a variable sized UITableViewCell?

I can't seem to get the text to actually span multiple lines. The heights look correct. What am I missing?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"StatusCell"] autorelease];
CGRect frame = cell.contentView.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame:frame];
myLabel.text = [[person.updates objectAtIndex:indexPath.row] valueForKey:#"text"];
[cell.contentView addSubview:myLabel];
[myLabel release];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *text = [[person.updates objectAtIndex:indexPath.row] valueForKey:#"text"];
UIFont *font = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize withinSize = CGSizeMake(tableView.frame.size.width, 1000);
CGSize size = [text sizeWithFont:font constrainedToSize:withinSize lineBreakMode:UILineBreakModeWordWrap];
return size.height + 20;
}
Also, what am I missing that makes the labels appear longer than the table cell?
Tweetero provides an example of this in MessageListController.m. The code there renders the following screen:
(Pic is taken from Mashable).
The basic implementation outline:
When constructing a UITableViewCell, create and add a UILabel as a subview in the manner shown in tableviewCellWithReuseIdentifier:. Look for the creation of TEXT_TAG label.
when enriching the UITableViewCell with views, ensure that you format label properly, as is done in configureCell:forIndexPath, similarly look for the label tag TEXT_TAG.
Return the appropriate height for each cell, as is done in tableView:heightForRowAtIndexPath.
myLabel.numberOfLines = 2;
Check the docs for full info on how to use this property.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return theSizeYouWantYourCellToBe;
}