Change the UITableViewCell Height According to Amount of Text - ios

I need to be able to adjust the height of a single cell in my UITableView so that it fits the amount of text in its detail label.
I have played with the following but it hasn't work for me:
How do I wrap text in a UITableViewCell without a custom cell
Attempted code:
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];
}
and
- (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;
}
This hasn't worked, it shows the entire string on the cell, however the cell height isn't affected at all.

Its simple, just add this to your code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
It automatically count an height of row and than return a float.

Hi Josh,
Using tableView:heightForRowAtIndexPath: you can give the size of each row at run time. now your problem is how to get height from your string there are function in NSString class by this code your problem,
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = [dataSourceArray objectAtIndex:indexPath.row];
CGSize size = [str sizeWithFont:[UIFont fontWithName:#"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"%f",size.height);
return size.height + 10;
}
by below line you set your label`s num. of line to max. so set it in cellForRowAtIndexPath: method.
cell.textLabel.numberOfLines = 0;
if you use some custom cell then manage all label`s string with this and get sum of all that height then set the height of your cell.
Edit :
iOS 8 onwards if you set proper autolayout constraints to label then you have to set only following delegate method to achieve this.
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
//minimum size of your cell, it should be single line of label if you are not clear min. then return UITableViewAutomaticDimension;
return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
that`s it. no any calculation required. For more information check this tutorial.

In your CustomCell: Remember to add the constraint top and bottom for your UILabel
For adjust UILabel height depend on text just change UILabel line to 0
(see the answer here)
Then in your code, just only set 2 line
self.tableView.estimatedRowHeight = 80;
self.tableView.rowHeight = UITableViewAutomaticDimension;
Here is my custom cell
Here is my UILabel constraints
The screen you will achieve
=== Suggestion ===
IF your cell has some UILabels and Images (not like my example) then:
You should put all UILabels and Images to one GroupView (View)
Add the constraint top and bottom to supper view for this GroupView (like the UILabel in my image)
Adjust UILabel height like the my suggestion above
Adjust the GroupView height depend on the content (the content is all UILabels and Images)
Finally, change estimateRowHeight and tableView.rowHeight like the code above
Hope this help

Based on the code you have provided, I think you are increasing only the cell height and not the cell.textLabel's height.
Ideally, you should set the frame size of cell.textLabel and the cell for you to see the full text in the cell.
A neat way to see whats wrong with a view in terms of size, is to color it different than the background (try setting cell.textLabel background to yellow) and see if the height is actually being set.
Here's how it should be
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
NSString *cellText = #"Go get some text for your cell.";
UIFont *cellFont = cell.textLabel.font;
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
cell.textlabel.frame.size = labelSize;
cell.text = cellText;
}
Hope this helps!
update: This is quite an old answer, and many lines in this answer may be deprecated.

For swift developers:
Custom cell:
At first you can calculate the height of the text like below:
func calculateHeight(inString:String) -> CGFloat
{
let messageString = inString
let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
let requredSize:CGRect = rect
return requredSize.height
}
Set the width of your text label
Then call this function:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
heightOfRow = self.calculateHeight(inString: conversations[indexPath.row].description)
return (heightOfRow + 60.0)
}
For Basic cell:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
This function will not work for custom cells.
Hope it will work.

In tableView:heightForRowAtIndexPath: you can take the text and use sizeWithFont:constrainedToSize: in order to get the size of the text.
Then just return the height plus some extra spacing for buffer.

You can write a method globally to make it so it can be used throughout the app. You need to pass the text, font and width as per your requirement.
In Swift 4:
func heightForText(text: String,Font: UIFont,Width: CGFloat) -> CGFloat{
let constrainedSize = CGSize.init(width:Width, height: CGFloat(MAXFLOAT))
let attributesDictionary = NSDictionary.init(object: Font, forKey:NSAttributedStringKey.font as NSCopying)
let mutablestring = NSAttributedString.init(string: text, attributes: attributesDictionary as? [NSAttributedStringKey : Any])
var requiredHeight = mutablestring.boundingRect(with:constrainedSize, options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), context: nil)
if requiredHeight.size.width > Width {
requiredHeight = CGRect.init(x: 0, y: 0, width: Width, height: requiredHeight.height)
}
return requiredHeight.size.height;
}

I was able to get this accomplished using autolayout. Make sure your label snaps to the top and bottom of the cell (I'm using a prototype cell), and it's lines set to 0. Then in the tableView:heightForRowAtIndexPath:sizeWithFont:constrainedToSize: you can set the height of the cell by doing the calculation on the text size:
NSString *key = self.detailContent.allKeys[indexPath.row];
NSDictionary *dictionary = self.detailContent[key];
NSString *cellText = dictionary[kSMDetailTableViewCellTextKey];
UIFont *cellFont = [UIFont fontWithName:kFontKeyEmondsans size:12.0];
CGSize constraintSize = CGSizeMake(252.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height;// + 10;

NSString *str;
NSArray* dictArr;
if (_index==0) {
dictArr = mustangCarDetailDictArr[indexPath.section];
}
NSDictionary* dict = dictArr[indexPath.row];
if (indexPath.section ==0)
{
str = [dict valueForKey:#"FeatureName"];
if ([[dict valueForKey:#"FeatureDetail"] isKindOfClass:[NSString class]])
{
str = [dict valueForKey:#"FeatureDetail"];
}
else
{
if (dictArr.count>indexPath.row+1)
{
NSDictionary* dict2 = dictArr[indexPath.row+1];
if ([[dict2 valueForKey:#"FeatureDetail"] isKindOfClass:[NSString class]])
{
}
}
}
}
CGSize size = [str sizeWithFont:[UIFont fontWithName:#"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"%f",size.height);
return size.height + 20;
}

Related

UITableView Dynamic Height not changing iOS

Drag and drop UITableViewHeader
You can look at an orange color UITextView.
I set the height constant of the tableview is zero.
After reloading the tableview total height of UITableView showing same as previous(as no UITextView showing)
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.heightConstCommentBox.constant = 0;
[self configureTableviewFooter];
}
-(void)configureTableviewFooter{
//More button Configure
height = 50 +[self recusiveDescription:self.viewFooter] ;
// Assign new frame
self.viewFooter.frame = CGRectMake(self.viewFooter.frame.origin.x,
self.viewFooter.frame.origin.y,self.viewFooter.frame.size.width , height); // viewFooter is container view of tableFooterView
self.tableView.tableFooterView = self.viewFooter;
[self.tableView reloadData];
}
- (float )recusiveDescription:(UIView *)view
{
NSString *s = #"";
float height = 0;
NSArray *subviews = [view subviews];
if ([subviews count] == 0) return 0;
for (UIView *subView in subviews) {
height = height + subView.frame.size.height ;
[self recusiveDescription:subView];
}
return height;
}
After reloading the tableview , table view footer size not changing.
In method recusiveDescription:(UIView *)view you use the frame property of the subview. But for the autolayout it is not correct. To get future size of the view, call:
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize
withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority
verticalFittingPriority:(UILayoutPriority)verticalFittingPriority;
This method returns the optimal size for the view based on the provided constraint priorities.
Also I did not understand why do you call recusiveDescription in recusiveDescription: and do not use result value.
u can use following in case u used custom cell for table.
in following code replace postss[index.row].post with your label content and +230 is minimum height of your cell.
or u can say its height of other view other than label.
automatic dimension method will work only if u have 1 label or 1 textfield,1 textview.
and don't fix your label's height.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let heightOfRow = self.calculateHeight(inString: postss[indexPath.row].post)
return (heightOfRow + 230)
}
//custom function for calculate dynamic height
func calculateHeight(inString:String) -> CGFloat
{
let messageString = inString
let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 15.0)]
let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes)
let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 370, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
let requredSize:CGRect = rect
return requredSize.height
}

GrowingTextView or expandable textview inside UItableview cell

I wish to implement an expandable textview inside the table cell, I found the GrowingTextView but I still failed to implement.I need to get input from user and the cell will auto resize when the users typing. Is there any easier implementation or guide on this? Thanks all
Actually you dont need 3rd party library to do this.
Change your GrowingTextView to UILabel
Config you UILabel to Top, Left, Right, and Bottom to the cell, and make "Title" label dependent on the UILabel
this is important because the cell size is dependant of the content of UILabel.
Set numberOfLines to 0 and
Set lineBreakMode to word wrapping or character warpping
Set tableView.rowHeight = UITableViewAutomaticDimension and tableView.estimatedRowHeight = 150 // or wtever you found reasonable
For task like these i suggest you can do more research on Internet instead of using a 3rd party library so fast, the keyword here is dynamic table view cell which by searching on Google there are lots of tutorials helping you out without using 3rd party library.
You can achieve it with native UITextView.
Implement this in the text view's delegate
- (void)textViewDidChange:(UITextView *)textView{
CGRect oldFrame = textView.frame;
CGSize constraint = CGSizeMake(yourTextViewWidth, MAXFLOAT);
CGRect rect = [textView.text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:textView.font} context:nil];
CGSize size = CGSizeMake(rect.size.width, rect.size.height);
[textView setFrame:CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.size.width, size.height + 5)];
// These 2 lines to force UITableView to redo the height calculation.
[self.yourTableView beginUpdates];
[self.yourTableView endUpdates];
}
Then, implement this in the table view's delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *yourTextViewText;
// You get the text either from the same way you did in cellForRowAtIndexPath dataSource
// or if you already referenced UITextView as your property you can easily retrieve the text by calling self.yourTextView.text
CGSize constraint = CGSizeMake(yourTextViewWidth, MAXFLOAT);
CGRect rect = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:yourFontSize]} context:nil];
CGSize size = CGSizeMake(rect.size.width, rect.size.height);
CGFloat height = MAX(size.height, yourDefaultCellHeight);
return height + 5;
}
UPDATE Swift version converted by Swiftify v4.1.6738 - https://objectivec2swift.com/
func textViewDidChange(_ textView: UITextView) {
let oldFrame: CGRect = textView.frame
let constraint = CGSize(width: yourTextViewWidth, height: MAXFLOAT)
let rect: CGRect = textView.text.boundingRect(with: constraint, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: textView.font], context: nil)
let size = CGSize(width: rect.size.width, height: rect.size.height)
textView.frame = CGRect(x: oldFrame.origin.x, y: oldFrame.origin.y, width: oldFrame.size.width, height: size.height + 5)
// These 2 lines to force UITableView to redo the height calculation.
yourTableView.beginUpdates()
yourTableView.endUpdates()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let yourTextViewText: String
// You get the text either from the same way you did in cellForRowAtIndexPath dataSource
// or if you already referenced UITextView as your property you can easily retrieve the text by calling self.yourTextView.text
let constraint = CGSize(width: yourTextViewWidth, height: MAXFLOAT)
let rect: CGRect = text.boundingRect(with: constraint, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: yourFontSize)], context: nil)
let size = CGSize(width: rect.size.width, height: rect.size.height)
let height: CGFloat = max(size.height, yourDefaultCellHeight)
return height + 5
}

How to resize table cell based on textview?

I have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class. Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.
I have the following in viewDidLoad of the tableview controller:
tableView.estimatedRowHeight = 56.0
tableView.rowHeight = UITableViewAutomaticDimension
Any idea why this isn't working?
Try my answer its work perfectly.
var record : NSArray = NSArray()
var hight: CGFloat = 0.0
Put this code in viewDidLoad()
record = ["I have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class." ,"Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:"," have a UITextView in a custom UITableViewCell. The textview delegate is assigned in the tableviewcell custom class.","Textview scrolling is disabled. Text loads into each textview and is multiline. But the text is always clipped because the cell height doesn't change.","I have the following in viewDidLoad of the tableview controller:","i just give you one link at put place i use label and you can now use your textview and give same constrain that i give in that link and try it so your problem will be solve","I have the following in viewDidLoad of the tableview controller:"];
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return record.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Textviewcell", forIndexPath: indexPath)
let textview: UITextView = (cell.viewWithTag(5) as! UITextView)
textview.text = record.objectAtIndex(indexPath.row) as? String
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// 7.1>
hight = self.findHeightForText(self.record.objectAtIndex(indexPath.row) as! String, havingWidth: self.view.frame.size.width - 10, andFont: UIFont.systemFontOfSize(14.0)).height
return 44 + hight
}
func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize {
var size = CGSizeZero
if text.isEmpty == false {
let frame = text.boundingRectWithSize(CGSizeMake(widthValue, CGFloat.max), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
size = CGSizeMake(frame.size.width, ceil(frame.size.height))
}
return size
}
In Swift 3.0
func findHeightForText(text: String, havingWidth widthValue: CGFloat, andFont font: UIFont) -> CGSize {
var size = CGSize.zero
if text.isEmpty == false {
let frame = text.boundingRect(with: CGSize(width: widthValue, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
size = CGSize(width: frame.size.width, height: ceil(frame.size.height))//CGSizeMake(frame.size.width, ceil(frame.size.height))
}
return size
}
Here are some screen shot .Storyboard
Runtime tableview with UITextView
You should use the delegate method
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
to set the height for the row. Then, inside that method, return the height that the cell should be by calculating the height of the textview which will occupy the space. You should use the function:
-(CGFloat)heightForTextViewRectWithWidth:(CGFloat)width andText:(NSString *)text withBuffer:(float)buffer
{
UIFont * font = [UIFont fontWithName:#"YourFontName" size:15.0f]; // Replace with your font name and size
NSDictionary *attributes = #{NSFontAttributeName: font};
// this returns us the size of the text for a rect but assumes 0, 0 origin, width is the width of that your text box will occupy.
// Ex. If you text box has padding of 12 both trailing and leading to the cell, then width should be the cell's width minus 24.
CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
// return height of rect
return rect.size.height;
}
This will determine the rect that your text view will occupy in the cell. The height that is returned is equal to the height of the text view, so if you want the cell to be taller than the text box, add that padding.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * yourText = commentDict.text; // or however you are getting the text
float widthPadding = 24.0f;
float heightPadding = 16.0f;
float height = [self heightForTextViewRectWithWidth: (tableView.frame.size.width - widthPadding) andText:yourText];
return height + heightPadding;
}
Hope this helped!

Dynamically Changing Frame of View Swift

I have a UICollectionView. The UICollectionViewCell contains a UITextView. I want to dynamically change the frame of the UITextView. I use the following code. The problem is that sometimes this works, other times it doesn't and no change is made to the frame. I am not sure what the issue is.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("message_cell" , forIndexPath: indexPath) as! DisplayMessageCollectionViewCell
if let messageText = "testing" {
let size = CGSizeMake(250, 1000)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let estimatedFrame = NSString(string: messageText).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(14)], context: nil)
if let user_id = NSUserDefaults.standardUserDefaults().stringForKey("userId") {
if (user_id == "testing") {
cell.messageTextView.frame = CGRectMake(view.frame.width - estimatedFrame.width - 16 - 8, 0, estimatedFrame.width + 16, estimatedFrame.height + 20)
}
else {
cell.messageTextView.frame = CGRectMake(48 + 3, 0, estimatedFrame.width + 15, estimatedFrame.height + 20 )
}
}
}
return cell
}
As discussed Here,
Adding trailing and leading NSLayoutConstraints to the messageTextView fixed the problem
If you are using AutoLayout just remove the width and height constraints on the text components and it will adapt accordingly to the text size.
Next thing you should do is to calculate the textSize of the string in
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize maximumLabelSize = CGSizeMake(yourCellWidth, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabelFont constrainedToSize:maximumLabelSize lineBreakMode: UILineBreakModeWordWrap];
return expectedLabelSize;
}
NOTE: If you don't have SizeClasses checked it will show you the yellow warnings because you don't have width and height set, but just ignore them.
UPDATE: You can find a good tutorial about this topic here.

Lazy Load Images in ios?

I am lazy loading some images in a table view
I followed the below tutorial
Lazy Load ios
This is the cell style which I want to display.
The problem is on the server side image is too big so the image view takes the full width and height of the image. Which results in an abrupt display of the table.
I cant reduce the size on the server. Isnt there any way with which I can set the image height and width for all images that are being lazy loaded.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"videoCell1";
CellTableViewCell *cell =(CellTableViewCell *)[tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"videoCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.videoNameLabel.text = [videoTitle objectAtIndex:indexPath.row];
cell.videoImage.contentMode = UIViewContentModeScaleAspectFill;
[cell.videoImage sd_setImageWithURL:[NSURL URLWithString:[videoImage objectAtIndex:indexPath.row]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 200;
}
Plus on scrolling the table view it also disrupts. How do I solve the issue? Any suggestions.
I would recommend looking at PHImageManager
Example code in swift
var assets: [PHAsset]
var imageRequests: [NSIndexPath: PHImageRequestID]
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let manager = PHImageManager.defaultManager()
if let request = imageRequests[indexPath] {
manager.cancelImageRequest(request)
}
let asset = assets[indexPath.row]
cell.textLabel?.text = NSDateFormatter.localizedStringFromDate(asset.creationDate, dateStyle: .MediumStyle, timeStyle: .MediumStyle)
imageRequests[indexPath] = manager.requestImageForAsset(asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .AspectFill, options: nil) { (result, _) in
cell.imageView?.image = result
}
return cell
}
The cell reusing is not properly implemented.
Add this code:
- (void)viewDidLoad
{
[super viewDidload];
[self.tableView registerNib:[UINib nibWithNibName:#"videoCell" bundle:nil]
forCellReuseIdentifier:#"videoCell1"];
}
And remove this code
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"videoCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
Before saving the image in your _diskCachePath, resize the image and then save. When you scroll the table view it will load smaller size images and it looks smooth scrolling.
For resizing the image use the following method. This will maintains the aspect ratio when resizing the image.
-(UIImage*) imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize{
CGFloat width = image.size.width;
CGFloat height = image.size.height;
if ((width/newSize.width) > (height/newSize.height)) {
if (width < newSize.width) {
newSize.width = width;
}
newSize.height = height*(newSize.width/width);
}
else if ((width/newSize.width) < (height/newSize.height)) {
if (height < newSize.height) {
newSize.height = height;
}
newSize.width = width*(newSize.height/height);
}
else if(newSize.width > width && newSize.height > height){
newSize.height = height;
newSize.width = width;
}
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}

Resources