UITableViewCell row height - objective-c

Is there any such method or solution to auto adjust row height of tableview depending on content.I mean that I don't want to specify row height and want row height according to content of the row.If there is no such method then tell me the solution that how can I change height when the orientation of the device changes ?

You will have to find the the height of the your content and can use it
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return "your content height + your padding height value";
}
On orientation change just reload your table view thats it;

check this out
// --dynamic cell height according to the text--
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = <your text>;
CGSize constraint = CGSizeMake(210, 20000.0f);
CGSize size = [text sizeWithFont:[UIFont fontWithName:#"Helvetica-Light" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
// constratins the size of the table row according to the text
CGFloat height = MAX(size.height,60);
return height + (15);
// return the height of the particular row in the table view
}
hope this helps
EDIT for the orientation have you tried this method?
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
or else if your table cells are custom with labels and imageviews etc then you can use setAutoresizingMask: on each to auto adjust to orientations.
[yourview setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

You can implement the
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
delegate method of UITableView.
You should be able to find plenty of tutorials about it if you google it.
Here's one for example:
http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

You HAVE to use:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
Yea - I know you know this method very well, and I have read your question carefully.
You have to use that delegate method to dynamically control the height of the rows. My suggestion is to examine the content at each cell from your backend data model for the tableview and return a number that is appropriate for that cell something like:
NSDictionary *thisCell = (NSDictionary *)[myArray objectAtIndexPath:indexPath.row];
NSString *myCellContents = [thisCell valueForKey:#"MyStringIWantToCheckOut"];
if ([mycellContents length] > 25) {
return 80;
} else {
return 40;
}
As far as when orientation changes, you would have to do that in the delegate method:
-(void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
and then fire reloadData on the TableView.

- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
switch (indexPath.row){
case 0:
if(indexPath.section == 0)
//title
return 75;
default:
return 75;
}
}

func tableView(_ heightForRowAttableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
for dynamic height for row otherwise you can give static height instead of "UITableViewAutomaticDimension"

Related

UITableviewCell automatic sizing based on label not working

UITableview cells are returning heights that don't really correlate to their text.
I have been dealing with a rather annoying bug where xcode returns incorrect heights for cells and just in general is return pixels heights for elements in cells that are terribly inconsistent.
I thought I could implement the methods below to clean things up, but they turned out just to make things worse.
The first image in the google doc is what my cells look like when I use these methods. Please tell me any ideas you have to fix them. The crux of the problem is a special case which I have shown in the second image of the google doc.
The reason behind the special case and a deeper discussion of the reason it occurs is in the google doc. Here's the google doc link:
https://docs.google.com/document/d/1tT43nE-1Wq8leRIaoQ29S0aQhZUWP88kIX3WlG_RcOg/edit?usp=sharing
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section==0) { //postcell
return 500.0; //TODO add some autolayout stuff for this case...
} else { //comment cell
UIFont * font=[UIFont fontWithName:#"Helvetica Neue" size:13.0];
NSIndexPath *adjustedIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section-1];
BRComment *comment = [self.commentsController objectAtIndexPath:adjustedIndexPath];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
//CommentCell * commentCell=(CommentCell *)[self.tableView cellForRowAtIndexPath:indexPath];
CGSize labelHeight = [self heigtForCellwithString:comment.body andLabelWidth:screenWidth-78.0 withFont:font];
return labelHeight.height; // the return height + your other view height
}
}
-(CGSize)heigtForCellwithString:(NSString *)stringValue andLabelWidth:(CGFloat)labelWidth withFont:(UIFont *)font{
CGSize constraint = CGSizeMake(labelWidth,9999); // Replace 300 with your label width //TODO replace
NSDictionary *attributes = #{NSFontAttributeName: font};
CGRect rect = [stringValue boundingRectWithSize:constraint
options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
return rect.size;
}
iOS 8 introduces the super handy UITableViewAutomaticDimension const to UITableView. To get cells to size themselves automatically simply return UITableViewAutomaticDimension from both -tableView:heightForRowAtIndexPath: and -tableView:estimatedHeightForRowAtIndexPath:.
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
Voila, your cells should be sized correctly. Note this'll also take into account cell layoutMargins and indentationWidth/indentationLevel if you need to use those.

Show only the first row in a UITableView

So, most of the questions are "my tableView only shows the first row, what's wrong?".
Well, what I need is exactly the opposite.
I have a SearchBar (not Search Display Controller) and until the user starts typing, I want to show ONLY the first row and nothing more.
My TableView's content is Dynamic Prototypes, with 2 Prototype Cells.
The first is the only one I want to show, but it shows others in blank.
https://www.dropbox.com/s/q4ak6z3gbc0gh5c/Screenshot%202014-07-22%2011.24.22.png
This is my tableView:numberOfRowsInSection:.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSInteger numberOfRows = 0;
if ([self.searchBar.text isEqualToString:#""]) {
numberOfRows = 1;
}
return numberOfRows;
}
All the help will be very appreciated! \o/
Probably there is a better solution, but as proposed before :
CGRect frame = [self.tableView frame];
frame.size.height = [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
self.tableView.frame = frame;
In your view controller's -tableView:numberOfRowsInSection: make sure tableView equals to self.tableView, and then you return 1:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return 1;
} else {
return yourDataModel.count;
}
}
You must change the size UITableView's contentView or frame at the creation (alloc).
This height must be the same of an UITableViewCell by default (44px) or custom.
Write the below 4 lines to make a table with one row. If you want to extend the content of the table just make the tableview scrollable.
tblView = [[UITableView alloc]initWithFrame:CGRectZero];
tblView.separatorColor = [UIColor clearColor];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
tblView.scrollEnabled = NO;

UIScrollView scrolling area inside a UICollectionViewCell

I have the following UICollectionView Controller
My problem is when I zoom into the image, I am able to "scroll past" the image boundary. It is almost exactly similar to this question Keep zoomable image in center of UIScrollView but the answer didn't solve it for me.
From what I understand, I believe this is because the content size of the scrollView isn't set to the size of the image. However, I'm not sure where to set something like self.scrollView.contentSize = self.imageView.image.size in my subclassed UICollectionViewCell.
Default View
Zoomed and Moved Beyond Image Boundary
My expected behaviour is for the image to sorta bounce back if the user tries to scroll beyond the image.
The relevant code thus far
Imgur Cell Subclass
- (void)awakeFromNib {
self.scrollView.minimumZoomScale = 1;
self.scrollView.maximumZoomScale = 3.0;
self.scrollView.delegate = self;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
View Controller
- (void)viewDidLoad {
[super viewDidLoad];
[self setStyle];
ImgurCellDetail *cell = (ImgurCellDetail *)[self.collectionView cellForItemAtIndexPath:self.indexPath];
cell.scrollView.minimumZoomScale = cell.scrollView.frame.size.width / cell.imageView.frame.size.width;
cell.scrollView.maximumZoomScale = 3.0;
cell.scrollView.contentSize = cell.imageView.image.size;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadSelectedImage];
}
- (void)loadSelectedImage
{
[self.collectionView scrollToItemAtIndexPath:self.indexPath
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:NO];
}
- (ImgurCellDetail *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
ImgurCellDetail *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
[self resetImage:cell];
cell.imageView.image = [UIImage imageWithContentsOfFile:self.imageArray[indexPath.row]];
[self.collectionView addGestureRecognizer:cell.scrollView.pinchGestureRecognizer];
[self.collectionView addGestureRecognizer:cell.scrollView.panGestureRecognizer];
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
// Need this for 3.5"
return self.collectionView.frame.size;
}
- (void)collectionView:(UICollectionView *)collectionView
didEndDisplayingCell:(ImgurCellDetail *)cell
forItemAtIndexPath:(NSIndexPath *)indexPath {
[self.collectionView removeGestureRecognizer:cell.scrollView.pinchGestureRecognizer];
[self.collectionView removeGestureRecognizer:cell.scrollView.panGestureRecognizer];
}
- (void)resetImage:(ImgurCellDetail *)cell {
//reset zoomScale back to 1 so that contentSize can be modified correctly
cell.scrollView.zoomScale = 1;
}
I should probably mention that I have no issues when the Image View is set to aspect fill but as you can see, it's currently set to aspect fit which is where my troubles begin.
I think you have to start by setting the contentSize of the scroll view to match the size of the scaled down size of your image (the size shown in your first screenshot) and not to the actual size of the picture.
// Not this
//cell.scrollView.contentSize = cell.imageView.image.size;
// But this
CGSize originalSize = cell.imageView.image.size;
CGSize sizeToFit = cell.scrollView.bounds.size;
CGFloat scaleDownFactor = MIN(sizeToFit.width / originalSize.width,
sizeToFit.height / originalSize.height);
CGSize scaledDownSize = CGSizeMake(nearbyintf(originalSize.width * scaleDownFactor),
nearbyintf(originalSize.height * scaleDownFactor));
cell.scrollView.contentSize = scaledDownSize;
// Also use scaledDownSize for the viewForZooming
From there you keep adjusting the content insets as done in the answer you linked.
Finally the scroll view's actual size may not be fully adjusted yet in viewDidLoad!
I managed to solve my own bug. I adapted the method found here: http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content into my solution.
The changes I had to make were:
Generating the image programmatically instead of using the storyboard
Adding scrollview min/max zoom init code in my awakeInNib method for my UICollectionView subclass
Generating the image in my cellForRowIndexPath
That's about it I think.

Dynamically size uitableViewCell according to UILabel (With paragraph spacing)

I have a UITableView which is populated by text and images from a JSON file. The TableView Cell is currently sizing correctly for "posts" that do not contain many line breaks in the text however I cannot get it to calculate the correct height for "posts" with 4 or 5 line breaks.
Code for getting height:
-(float)height :(NSMutableAttributedString*)string
{
NSString *stringToSize = [NSString stringWithFormat:#"%#", string];
CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);
CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:contraint lineBreakMode:NSLineBreakByWordWrapping];
return size.height;
}
How do I calculate the correct size while allowing for line breaks and white space?
EDIT
The Rest of the method,
Inside of TableView CellForRow:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *row = [NSString stringWithFormat:#"%i", indexPath.row];
float postTextHeight = [self height:postText];
NSString *height = [NSString stringWithFormat:#"%f", heightOfPostText + 70];
[_cellSizes setObject:height forKey:row];
}
And the height of Table Cell:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *imageHeightString = [NSString stringWithFormat:#"%#", [_cellSizes objectForKey:indexPath.row]];
float heightOfCell = [imageHeightString floatValue];
if (heightOfCell == 0) {
return 217;
};
return heightOfCell + 5;
}
better u need to calculate the height first, don't include the height calculation part in method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Better to calculate it in method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
since u are getting the data from json it is easy for u to calculate
in the "heightForRowAtIndexPath" method.
follwing code will give the example to calculate height of text change it ur requirement.
hopee this helps u :)
// i am using an array
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIFont *labelFont = [UIFont fontWithName:#"Noteworthy-Bold" size:20];
NSDictionary *arialdict = [NSDictionary dictionaryWithObject:labelFont forKey:NSFontAttributeName];
NSMutableAttributedString *message = [[NSMutableAttributedString alloc] initWithString:#"this is just the sample example of how to calculate the dynamic height for tableview cell which is of around 7 to 8 lines. you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];
array = [NSMutableArray arrayWithObjects:message, nil];
NSMutableAttributedString *message_1 = [[NSMutableAttributedString alloc] initWithString:#"you will need to set the height of this string first, not seems to be calculated in cellForRowAtIndexPath method." attributes:arialdict];
[array addObject:message_1];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *Cell = [self.aTableView dequeueReusableCellWithIdentifier:#"cell"];
if(Cell == nil)
{
Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
//dont include the height calculation part hear, becz heights are already set for all the cell
[Cell.textLabel sizeToFit];
Cell.textLabel.attributedText = [array objectAtIndex:indexPath.row]; // dont calculate height hear it will be called after "heightForRowAtIndexPath" method
Cell.textLabel.numberOfLines = 8;
return Cell;
}
// put ur height calculation method i took some hardcoded values change it :)
-(float)height :(NSMutableAttributedString*)string
{
/*
NSString *stringToSize = [NSString stringWithFormat:#"%#", string];
// CGSize constraint = CGSizeMake(LABEL_WIDTH - (LABEL_MARGIN *2), 2000.f);
CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height //set the constant width, hear MAXFLOAT gives the maximum height
CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:20.0f] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
return size.height; //finally u get the correct height
*/
//commenting the above code because "sizeWithFont: constrainedToSize:maxSize: lineBreakMode: " has been deprecated to avoid above code use below
NSAttributedString *attributedText = string;
CGRect rect = [attributedText boundingRectWithSize:(CGSize){225, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];//you need to specify the some width, height will be calculated
CGSize requiredSize = rect.size;
return requiredSize.height; //finally u return your height
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//whatever the height u need to calculate calculate hear only
CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]];
NSLog(#"%f",heightOfcell);
return heightOfcell;
}
Hope this helps u :)
For SWIFT version
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
var messageArray:[String] = [] //array to holde the response form son for example
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background",
"In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn’t exist anymore. In such case the system will relaunch the app in the background.",
" If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn’t seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.",
]
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return messageArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell;
if(cell == nil)
{
cell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier: "CELL")
cell?.selectionStyle = UITableViewCellSelectionStyle.None
}
cell?.textLabel.font = UIFont.systemFontOfSize(15.0)
cell?.textLabel.sizeToFit()
cell?.textLabel.text = messageArray[indexPath.row]
cell?.textLabel.numberOfLines = 0
return cell!;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row])
return height + 70.0
}
func calculateHeightForString(inString:String) -> CGFloat
{
var messageString = inString
var attributes = [UIFont(): UIFont.systemFontOfSize(15.0)]
var attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
var rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )
var requredSize:CGRect = rect
return requredSize.height //to include button's in your tableview
}
}
#Shan had a good answer but it didn't entirely worked for me.
This is the code I used for calculating the cell height
-(float)height :(NSMutableAttributedString*)string
{
CGRect rect = [string boundingRectWithSize:(CGSize){table.frame.size.width - 110, MAXFLOAT} options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return rect.size.height;
}
I do the -110 because that will give equal space at sides top and bottom.
Hope this helps.
Implement this table view delegate method:
-tableView:heightForRowAtIndexPath:
https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:
You'll call your method for determining the height and return that value with some extra padding if you wanted.
The approach I recommend is to set the text of an actual label and get the required height by calling sizeToFit. For this to work, you've got to set the label's numberOfLines property to 0 and set the desired maximum width.
When using this technique with table views, you can use the prototype cell method discussed here to calculate height using an actual cell.

Multiple clicks on uitableviewcell

Is there some way to change uitableview cell size according to the click on cell? For example: cell with width 100.0f, on first click cell changes width to 150.0f and for second click cell changes width back to 100.0f. How can I do this?
You should be able to index an NSMutableDictionary with NSIndexPath objects. This will let you cache the sizes you want for your clicked TVCells. Then just pull them out at runtime:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *newHeight;
NSNumber *height = [[self heightCache] objectForKey:indexPath];
if (height == nil) newHeight = [NSNumber numberWithFloat:100.0];
else newHeight = [NSNumber numberWithFloat:[height doubleValue] + 50];
[[self heightCache] setObject:newHeight forKey:indexPath];
[tableView reloadData]; // also consider reloadRowsAtIndexPaths:
}
Meanwhile in your delegate:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber height = [heightCache objectForKey:indexPath];
return height == nil ? defaultHeight : [height floatValue];
}
UPDATE: Oh oops, I thought you meant the TVCells to just get bigger and bigger. Yes, just change the floats in my example to bools, and then in height for row return the height based on the bool.
You need to maintain a bool value, change this bool value on each subsequent click.
Now based upon this bool define your cellForRowAtIndexPathmethod and on didSelectRowAtIndexPath method just update the bool and reload the table.