Tableview scroll slow down due to Method call - ios

In my tableview cell, there is a label for Description. The description text will be highlighted through Attributed Text in separate method. this method is call from cellforRowIndexPath & that's why tableview scroll is lagging a lot.
My code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SearchVCCell *cell = (SearchVCCell *)[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SearchVCCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.lbl_title.text=[NSString stringWithFormat:#"%#",[arrTitle objectAtIndex:indexPath.row]];
cell.lbl_disc.text=[NSString stringWithFormat:#"%#",[arrDescription objectAtIndex:indexPath.row]];
cell.lbl_page.text=[NSString stringWithFormat:#"Page: %d",[[arrPageNumber objectAtIndex:indexPath.row]intValue]];
int p= [self highlightText:_search_bar.text :cell.lbl_disc]; //Method Call
cell.lbl_count.text=[NSString stringWithFormat:#"%d",p];
}
return cell;
}
HightText Method:
-(int) highlightText :(NSString *)srcTxt :(UILabel*)txtView {
int srcTxtLen = srcTxt.length;
int idx = 0,count=0;
while (idx<(txtView.text.length-srcTxtLen)) {
NSRange srcRange = NSMakeRange(idx, srcTxtLen);
if ([[txtView.text substringWithRange:srcRange] isEqualToString:srcTxt]) {
NSMutableAttributedString *tmpAttrTxt = [[NSMutableAttributedString alloc] initWithAttributedString:txtView.attributedText];
[tmpAttrTxt addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:srcRange];
txtView.attributedText = tmpAttrTxt;
idx += srcTxtLen;
count++;
} else {
idx++;
}
}
return count;
}
Help me to solve, Thanks in advance

you can replace your method call with this
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:cell.lbl_disc.text];
NSRange range=[cell.lbl_disc.text rangeOfString:_search_bar.text];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:range];
[self.textToSpeak setAttributedText:string];

use this method:
- (NSMutableAttributedString*) setColor:(UIColor*)color forWord:(NSString*)word inText:(NSMutableAttributedString*)string {
NSUInteger count = 0, length = [string length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[string string] rangeOfString:word options:0 range:range];
if(range.location != NSNotFound) {
[string setTextColor:color range:NSMakeRange(range.location, [word length])];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return string;
}
and in your tableview cell call this
cell.lbl_disc.text= [self setColor:[UIColor yellowColor] forWord:_search_bar.text inText:[[NSMutableAttributedString alloc] initWithAttributedString:[NSString stringWithFormat:#"%#",[arrDescription objectAtIndex:indexPath.row]]]];

Related

UILabel or UIButton something like "view more" when UILabel text length bigger

In my app i have used to table view. In my list i have some cell label's texts bigger so i want to add View more or read more button or label after label text. Please suggest me how can i do that.
I have done with it. It is successuflly but it doesn't work read more gesture
- (void)addReadMoreStringToUILabel:(UILabel*)label
{
NSString *readMoreText = #"...Read More";
NSInteger lengthForString = label.text.length;
if (lengthForString >= 50)
{
NSInteger lengthForVisibleString = [self fitString:label.text intoLabel:label];
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:label.text];
NSString *trimmedString = [mutableString stringByReplacingCharactersInRange:NSMakeRange(lengthForVisibleString, (label.text.length - lengthForVisibleString)) withString:#""];
NSInteger readMoreLength = readMoreText.length;
NSString *trimmedForReadMore = [trimmedString stringByReplacingCharactersInRange:NSMakeRange((trimmedString.length - readMoreLength), readMoreLength) withString:#""];
NSMutableAttributedString *answerAttributed = [[NSMutableAttributedString alloc] initWithString:trimmedForReadMore attributes:#{NSFontAttributeName : label.font}];
NSMutableAttributedString *readMoreAttributed = [[NSMutableAttributedString alloc] initWithString:readMoreText attributes:#{NSFontAttributeName :[UIFont fontWithName:#"Roboto-Light" size:13.0] ,NSForegroundColorAttributeName :[UIColor blueColor]}];
[answerAttributed appendAttributedString:readMoreAttributed];
label.attributedText = answerAttributed;
label.userInteractionEnabled = YES;
UITapGestureRecognizer *readMoreGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(readMoreDidClickedGesture:)];
readMoreGesture.numberOfTapsRequired = 1;
[label addGestureRecognizer:readMoreGesture];
}
else {
NSLog(#"No need for 'Read More'...");
}
}
- (NSUInteger)fitString:(NSString *)string intoLabel:(UILabel *)label
{
UIFont *font = label.font;
NSLineBreakMode mode = label.lineBreakMode;
CGFloat labelWidth = label.frame.size.width;
CGFloat labelHeight = label.frame.size.height;
CGSize sizeConstraint = CGSizeMake(labelWidth, CGFLOAT_MAX);
NSDictionary *attributes = #{ NSFontAttributeName : font };
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:string attributes:attributes];
CGRect boundingRect = [attributedText boundingRectWithSize:sizeConstraint options:NSStringDrawingUsesLineFragmentOrigin context:nil];
{
if (boundingRect.size.height > labelHeight)
{
NSUInteger index = 0;
NSUInteger prev;
NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
do
{
prev = index;
if (mode == NSLineBreakByCharWrapping)
index++;
else
index = [string rangeOfCharacterFromSet:characterSet options:0 range:NSMakeRange(index + 1, [string length] - index - 1)].location;
}
while (index != NSNotFound && index < [string length] && [[string substringToIndex:index] boundingRectWithSize:sizeConstraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height <= labelHeight);
return prev;
}
}
/*if (SYSTEM_VERSION_GREATER_THAN(iOS7))
{
}
else
{
if ([string sizeWithFont:font constrainedToSize:sizeConstraint lineBreakMode:mode].height > labelHeight)
{
NSUInteger index = 0;
NSUInteger prev;
NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
do
{
prev = index;
if (mode == NSLineBreakByCharWrapping)
index++;
else
index = [string rangeOfCharacterFromSet:characterSet options:0 range:NSMakeRange(index + 1, [string length] - index - 1)].location;
}
while (index != NSNotFound && index < [string length] && [[string substringToIndex:index] sizeWithFont:font constrainedToSize:sizeConstraint lineBreakMode:mode].height <= labelHeight);
return prev;
}
}*/
return [string length];
}
- (void)readMoreDidClickedGesture:(UITapGestureRecognizer*)sender
{
UIView *view = sender.view;
NSLog(#"%ld", (long)view.tag); //By tag, you can find out where you had tapped.
}
I don't know what happen here. If any thing wrong in this code so please help me
It's everything ok with this code,, it works fine,,
May be you did not add in cellForRowAtIndexPath: method ?? here is simple code, it works fine
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
-
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.cellText.text = #"Label Label Label Label Label LabelLabel Label LabelLabel Label LabelLabel Label LabelLabel Label LabelLabel Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label vLabel Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label Label";
[self addReadMoreStringToUILabel:cell.cellText];
return cell;
}

Appending NSString and NSMutableAttributedString

I want to merge NSString and NSMutableAttributedString .
In below code i want to make self.txtSearch as custom bold size and color.
code -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
SearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SearchViewCell"];
AutoSuggestModel *autoSuggestModel = [self.autoSuggestArray objectAtIndex:indexPath.row];
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.lblText.text = [NSString stringWithFormat:#"%# in %#", self.txtSearch , [autoSuggestModel label]] ;
}else{
cell.lblText.text = [autoSuggestModel label];
}
return cell;
}
I could make bold particular string with below code. but i want to append both string.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc] initWithString:self.txtSearch];
NSRange boldRange = [[autoSuggestModel label] rangeOfString:self.txtSearch];
[boldString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:boldRange];
[cell.lblText setAttributedText: boldString];
update you method like bellow
if ([[autoSuggestModel type] isEqualToString:#"product"] || [[autoSuggestModel type] isEqualToString:#"category"]){
cell.textLabel.attributedText = [self getBoldText:cell withSearch:#"search text" withAutoSuggestModel:#"autoSuggestModel"];
}else{
cell.lblText.text = [autoSuggestModel label];
}
//check above code by the following method
-(NSMutableAttributedString*)getBoldText:(UITableViewCell*)cell withSearch:(NSString*)searchText withAutoSuggestModel:(NSString*)autoSuggestModelText{
NSString *title = [NSString stringWithFormat:#"%# in %#", searchText,autoSuggestModelText];
cell.textLabel.text = title;
UIColor *color = [UIColor redColor];
UIFont *font = [UIFont boldSystemFontOfSize:16];
NSDictionary *attrs = #{NSForegroundColorAttributeName : color,NSFontAttributeName:font};
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithAttributedString:cell.textLabel.attributedText];
[attrStr addAttributes:attrs range:[title rangeOfString:autoSuggestModelText]];
return attrStr;
}
A very cursory look at the NSString documentation has a section called "combining strings" and a method called stringByAppendingString:
Using this method, it should be incredibly straight-forward to accomplish what you're trying to do.
NSMutableAttributedString *boldString = [[NSMutableAttributedString alloc]
initWithString:[self.txtSearch stringByAppendingString:yourMutableString]];

Duplicate cells are getting created in iOS?

I have a created a custom cell in iOS.In custom cell there are many labels.For few labels the data of first & fourth custom cell is always same.There are total 5 records in my data source array.Now there are these issues i face.
Why cell for row at index is called only two times when there are 4 records in array.
Data of first & 4th row is always same.
Please tell me how can i resolve this issue.
CODE:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"cell for row called %d",(int)[arr_post count]);
//define variables here
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
static NSString *CellIdentifier = #"homeCell";
float x_pos;
HomeCell *cell = [self.table_view
dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//get the post data
Post *user_post=[arr_post objectAtIndex:indexPath.row];
cell.tv_post.text=user_post.post_description;
cell.tv_post.font = [UIFont fontWithName:user_post.font_family size:[user_post.font_size floatValue]];
cell.label_name.text=user_post.post_title;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:user_post.modification_date];
if([user_post.post_image isEqualToString:#"none"] && [user_post.post_video isEqualToString:#"none"])
{
x_pos=cell.tv_post.frame.origin.x;
cell.tv_post_leading_space.constant=-(x_pos);
[cell.img_post setHidden:true];
}
//set the like count
NSString *first_like_user=user_post.recent_like_name;
int count=(int)[first_like_user length];
float like_count=[user_post.like_count intValue];
//chek if tehre are any likes on the post
NSLog(#"recent like name is %#",user_post.recent_like_name);
NSLog(#"like count is %f",like_count);
if(like_count>0)
{
NSLog(#"inside like count block");
NSString *str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count-1];
if(like_count==1)
{
if([myUsername isEqualToString:first_like_user])
{
first_like_user=#"You like this post";
count=3;
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" like this post"];
}
}
else if(like_count==2)
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" other like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
if(like_count>1000)
{
like_count=like_count/1000;
str_like_count=[NSString stringWithFormat:#"%lu",(unsigned long)like_count];
str_like_count=[str_like_count stringByAppendingString:#"k"];
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
else
{
first_like_user=[first_like_user stringByAppendingString:#" and "];
str_like_count=[str_like_count stringByAppendingString:#" others like this post"];
first_like_user=[first_like_user stringByAppendingString:str_like_count];
}
}
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
//set the like label dynamic height & width
cell.label_like_count.attributedText = mutableAttributeStr;
CGSize maximumLabelSize = CGSizeMake(187,9999);
CGSize requiredSize = [cell.label_like_count sizeThatFits:maximumLabelSize];
CGRect labelFrame = cell.label_like_count.frame;
labelFrame.size.height = requiredSize.height;
cell.label_like_count.frame = labelFrame;
// cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping;
cell.label_like_count.numberOfLines = 0;
[cell.label_like_count sizeToFit];
[cell.label_like_count setAttributedText:mutableAttributeStr];
}
//show dynamic comment
NSMutableArray *user_comments=user_post.comments;
float comment_count=[user_post.comment_count intValue];
NSLog(#"arr comments count is %lu",(unsigned long)comment_count);
if(comment_count>0)
{
NSLog(#"post id is %#",user_post.id);
NSMutableAttributedString *mutableAttributeStr;
NSAttributedString *attributeStr;
for(l=0;l<[user_comments count];l++)
{
NSLog(#"inside loop %d",l);
Comment *comment=[user_comments objectAtIndex:l];
if(l==0)
{
NSLog(#"l is zero");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSLog(#"comment string is %#",comment_string);
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.first_comment setAttributedText:mutableAttributeStr];
}
else if(l==1)
{
NSLog(#"l is 1");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
NSLog(#"comment string is %#",comment_string);
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.second_cmment setAttributedText:mutableAttributeStr];
}
else if(l==2)
{
NSLog(#"l is 2");
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
[cell.third_comment setAttributedText:mutableAttributeStr];
}
}
}
else
{
NSLog(#"not inside loop");
}
cell.label_time.text=[BaseController getTimestampForDate:date];
return cell;
}
EDIT:
I have read somewhere that for performance reasons UITable resume the cell.Because i feel i get this issue when there are more than 3 rows.
EDIT:
I have found a strange situation here if i try don't use the condition if(like_count>0) & simply set the text fo label with out this condition then it works fine for me.
Thanks in advance.
Cell are reused, so you have to cover all case in your execution path.
As you already found, if(like_count>0) and if(comment_count>0) imply that if there is no count, the text label is not changed and the old value will stay there.
You have to add } else { cell.label_like_count.attributedText = nil } kind of code to cover all cases. Alternatively, you can add some cleanup code in - (void)prepareForReuse in the cell class (don't forget [super prepareForReuse]).
in HomeCell override prepareForReuse:. In that method, set the .text (or .attributedText) property to nil on all of your labels. Then see what happens.
Cells are reused and the table always creates only the cells that are currently visible. When you show the screen, three cells will be visible. When you scroll and one cell becomes hidden and another one appears, it's actually the same cell instance.
The usual way to handle this behavior is to subclass UITableViewCell and do all that setup there. The reset to a default state can be added to -prepareForReuse method, e.g.
- (void)prepareForReuse {
[super prepareForReuse];
self.first_comment.text = nil;
self.second_comment.text = nil;
self.third_comment.text = nil;
}
To fix your code without having a specific cell subclass, let's first simplify by removing the repetitive patterns from your code:
for (NSUInteger i = 0; i < [user_comments count]; i++) { //i is the traditional variable name for iterating
Comment *comment = user_comments[i]; //updating to newer syntax
// start of the repetitive pattern
NSString *comment_string=[comment.user_name stringByAppendingString:#" "];
comment_string=[comment_string stringByAppendingString:comment.comment];
int count=(int)[comment.user_name length];
NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
// end of the repetitive pattern
if (i == 0) {
[cell.first_comment setAttributedText:mutableAttributeStr];
}
else if (i == 1) {
[cell.second_comment setAttributedText:mutableAttributeStr];
}
else if (i == 2) {
[cell.third_comment setAttributedText:mutableAttributeStr];
}
}
Now you can combine it with resetting the value:
NSArray *commentLabels = #[cell.first_comment, cell.second_comment, cell.third_comment];
for (NSUInteger i = 0; i < 3; i++) {
UILabel *label = commentLabels[i];
// reset if there is no comment
if (i >= [user_comments count]) {
label.text = nil;
continue;
}
Comment *comment = user_comments[i];
NSString *comment_string = [NSString stringWithFormat:#"%# %#", comment.user_name, comment.comment];
int count = (int)[comment.user_name length];
NSMutableAttributedString* mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:comment_string];
NSAttributedString attributeStr = [[NSAttributedString alloc]initWithString:#"\n" attributes:#{NSFontAttributeName : [UIFont fontWithName:#"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:#"Helvetica-Bold" size:14.0 range:NSMakeRange(0, count)];
[mutableAttributeStr addAttribute:NSForegroundColorAttributeName value:[self colorFromHexString:#"#48a0dd"] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
label.attributedText = mutableAttributeStr;
}
Check the number of elements in the table and be sure the number is correct in the delegate numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return the_correct_items_number;
}
If the count is correct, try with a local array (just for test). Note: if you update the source array using network requests, consider to use the dispatch_async calling to update you content.
Use methods prepareForReuse in your custom cell .
// if the cell is reusable (has a reuse identifier), this is called just before the cell is returned from the table view method dequeueReusableCellWithIdentifier:. If you override, you MUST call super.
- (void) prepareForReuse {
// set empty or nil of your repeated element .
[super prepareForReuse];
}
hope it help you .
try replacing
if (cell==nil)
{
cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
with
//if (cell==nil)
//{
cell = [[HomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
After you dequeue cell, write the below line:-
[cell.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];

how to dynamically change the textview height and cell height according to the text length without the scroll

this is my code that shows data in table,my complete data is not showing in cell.
1st image is when i set scrollable to no ,2nd image when i do not set scrollable.i am a beginner.plz help me out of this.
- (void)textViewDidChange:(UITextView *)textView{
[table beginUpdates];
[table endUpdates];
}
-(void)createdatabase{
BOOL success;
NSFileManager *filemanager = [NSFileManager defaultManager];
success = [filemanager fileExistsAtPath:datapath];
if (success)return;
NSString *databasefromapp = [[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:dataname];
[filemanager copyItemAtPath:databasefromapp toPath:datapath error:nil];
}
-(void)getdatabase{
eventitleary = [[NSMutableArray alloc]init];
eventdescary = [[NSMutableArray alloc]init];
eventimgary = [[NSMutableArray alloc] init];
sqlite3 *dataname1;
if (sqlite3_open([datapath UTF8String],&dataname1) == SQLITE_OK) {
const char *sqlStatement;
sqlStatement = "SELECT * FROM photography_events";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(dataname1, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// Read the data from the result row
NSString *str_title = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
[eventitleary addObject:str_title];
NSString *str_desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
[eventdescary addObject:str_desc];
NSData *data = [[NSData alloc] initWithBytes:sqlite3_column_blob(compiledStatement, 2) length:sqlite3_column_bytes(compiledStatement, 2)];
[eventimgary addObject:data];
}
}
}
NSLog(#"%#", eventitleary);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return eventitleary.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellidenti = #"CellIdenti";
TableViewCell2 *cell = (TableViewCell2*)[tableView dequeueReusableCellWithIdentifier:cellidenti];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"TableViewCell2" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.eventitlelbl.text = [eventitleary objectAtIndex:indexPath.row];
cell.eventdesc.text = [eventdescary objectAtIndex:indexPath.row];
cell.eventdesc.editable = NO;
//cell.eventdesc.scrollEnabled = NO;
[cell.eventdesc sizeToFit];
frame = cell.eventdesc.frame;
frame.size = cell.eventdesc.contentSize;
cell.eventdesc.frame = frame;
NSData *dataimg = (NSData*)[eventimgary objectAtIndex:indexPath.row];
cell.eventimg.image = [UIImage imageWithData:dataimg];
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
// Return the height with a bit of additional padding space
return frame.size.height + 300;
}
You can achieve this by adaptive layout. Check this awesome tutorial if you are working with autolayout. Else you can set dynamic tableView cell height by calculating the height in which your text will fit.
You can calculate height of text by using below method. Pass text, required font and width of your textview.
-(CGFloat)heightForText:(NSString*)text withFont:(UIFont *)font andWidth:(CGFloat)width
{
CGSize constrainedSize = CGSizeMake(width, MAXFLOAT);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > width) {
requiredHeight = CGRectMake(0,0,width, requiredHeight.size.height);
}
return requiredHeight.size.height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [self heightForText:#"your text view text for this row" withFont:[UIFont fontWithName:#"Helvetica" size:16] andWidth:320];
}
i just got it, i wanted to do it dynamically rather than using auto layout,here is my code.Hope in future it works out to anyone.

UITableView loading wrong prototype cell from storyboard

I am having a really weird error that I cannot figure out, I really need some help right now. Basically, the tableView has three UITableViewCell subclasses that have their own prototype cell, and appear in their own section. But the prototype that is in the third section is also appearing in the second section. The weird part is that after putting some NSLogs into my code, the cell that is showing up in the second section section (which should be in the third section) is the correct subclass of UITableViewCell, but the content from the other prototype is showing up. I have no idea why this is happening. I have check to make sure the prototypes are of the right subclass, and the identifiers are all correct, and they are. Has anyone encountered this problem before? Sorry in advance for how long my cellForRowAtIndexPath: method is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
WaveDetailCell *waveDetails;
ActionsCell *actions;
CommentCell *comments;
id cellToReturn;
if (self.hasAgrees || self.hasComments)
{
switch (indexPath.section)
{
case 0:
{
waveDetails = [tableView dequeueReusableCellWithIdentifier:WaveDetailCellIdentifier forIndexPath:indexPath];
if ([waveDetails.waveLabel respondsToSelector:#selector(setAttributedText:)])
{
NSString *name = self.currentWaveObject.wavedToUserID;
NSString *fullWaveString = [name stringByAppendingString:self.currentWaveObject.waveString];
NSRange range = [fullWaveString rangeOfString:self.currentWaveObject.wavedToUserID];
UIFont *font = [UIFont fontWithName:HelveticaMedium size:16.0f];
NSDictionary *attrs = #{NSFontAttributeName: font};
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullWaveString];
[attributedString addAttributes:attrs range:range];
[waveDetails.waveLabel setAttributedText:attributedString];
}
waveDetails.wavedByNameLabel.text = self.currentWaveObject.wavedByUserID;
waveDetails.timestampLabel.text = self.currentWaveObject.creationDate;
//round the corners of the imageview
[self setCornerRadiusForImageView:waveDetails.profilePicImageView withRadius:CGSizeMake(4.0f, 4.0f)];
[self setCornerRadiusForImageView:waveDetails.waverProfileImageView withRadius:CGSizeMake(2.0f, 2.0f)];
cellToReturn = waveDetails;
}
break;
case 1:
{
if (self.hasAgrees)
{
//create agrees cell
}
else
{
actions = [tableView dequeueReusableCellWithIdentifier:ActionsCellIdentifier forIndexPath:indexPath];
cellToReturn = actions;
}
}
case 2:
{
if (self.hasAgrees)
{
//if there are agrees, and no comments, then the last section should be the actions cell
actions = [tableView dequeueReusableCellWithIdentifier:ActionsCellIdentifier forIndexPath:indexPath];
cellToReturn = actions;
}
else
{
//there are comments, and no agrees
comments = [tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier forIndexPath:indexPath];
CommentObject *comment = [self.currentWaveObject.commentsArray objectAtIndex:indexPath.row];
comments.userNameLabel.text = comment.commenterID;
comments.commentLabel.text = comment.commentText;
comments.timeStampLabel.text = comment.timeStamp;
[self setCornerRadiusForImageView:comments.userImageView withRadius:CGSizeMake(3.0f, 3.0f)];
cellToReturn = comments;
}
}
default:
break;
}
}
else if (self.hasComments && self.hasAgrees)
{
switch (indexPath.section)
{
case 0:
{
waveDetails = (WaveDetailCell *)[tableView dequeueReusableCellWithIdentifier:WaveDetailCellIdentifier forIndexPath:indexPath];
if ([waveDetails.waveLabel respondsToSelector:#selector(setAttributedText:)])
{
NSString *name = self.currentWaveObject.wavedToUserID;
NSString *fullWaveString = [name stringByAppendingString:self.currentWaveObject.waveString];
NSRange range = [fullWaveString rangeOfString:self.currentWaveObject.wavedToUserID];
UIFont *font = [UIFont fontWithName:HelveticaMedium size:16.0f];
NSDictionary *attrs = #{NSFontAttributeName: font};
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullWaveString];
[attributedString addAttributes:attrs range:range];
[waveDetails.waveLabel setAttributedText:attributedString];
}
waveDetails.wavedByNameLabel.text = self.currentWaveObject.wavedByUserID;
waveDetails.timestampLabel.text = self.currentWaveObject.creationDate;
//round the corners of the imageview
[self setCornerRadiusForImageView:waveDetails.profilePicImageView withRadius:CGSizeMake(4.0f, 4.0f)];
[self setCornerRadiusForImageView:waveDetails.waverProfileImageView withRadius:CGSizeMake(0.5f, 0.5f)];
cellToReturn = waveDetails;
}
break;
case 1:
{
//create agrees cell
}
break;
case 2:
{
actions = (ActionsCell *)[tableView dequeueReusableCellWithIdentifier:ActionsCellIdentifier forIndexPath:indexPath];
cellToReturn = actions;
}
break;
case 3:
{
comments = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier forIndexPath:indexPath];
CommentObject *comment = [self.currentWaveObject.commentsArray objectAtIndex:indexPath.row];
comments.userNameLabel.text = comment.commenterID;
comments.commentLabel.text = comment.commentText;
comments.timeStampLabel.text = comment.timeStamp;
[self setCornerRadiusForImageView:comments.userImageView withRadius:CGSizeMake(2.0f, 2.0f)];
cellToReturn = comments;
}
break;
default:
break;
}
}
else
{
if (indexPath.row == 0)
{
waveDetails = (WaveDetailCell *)[tableView dequeueReusableCellWithIdentifier:WaveDetailCellIdentifier forIndexPath:indexPath];
if ([waveDetails.waveLabel respondsToSelector:#selector(setAttributedText:)])
{
NSString *name = self.currentWaveObject.wavedToUserID;
NSString *fullWaveString = [name stringByAppendingString:self.currentWaveObject.waveString];
NSRange range = [fullWaveString rangeOfString:self.currentWaveObject.wavedToUserID];
UIFont *font = [UIFont fontWithName:HelveticaMedium size:16.0f];
NSDictionary *attrs = #{NSFontAttributeName: font};
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullWaveString];
[attributedString addAttributes:attrs range:range];
[waveDetails.waveLabel setAttributedText:attributedString];
}
waveDetails.wavedByNameLabel.text = self.currentWaveObject.wavedByUserID;
waveDetails.timestampLabel.text = self.currentWaveObject.creationDate;
//round the corners of the imageviews
[self setCornerRadiusForImageView:waveDetails.profilePicImageView withRadius:CGSizeMake(4.0f, 4.0f)];
[self setCornerRadiusForImageView:waveDetails.waverProfileImageView withRadius:CGSizeMake(0.5f, 0.5f)];
cellToReturn = waveDetails;
}
else
{
actions = (ActionsCell *)[tableView dequeueReusableCellWithIdentifier:ActionsCellIdentifier forIndexPath:indexPath];
cellToReturn = actions;
}
}
return cellToReturn;
}
Wait, I figured it out. This is embarrassing, but I forgot a break in one of the cases in the switch statement!

Resources