UITableview slow scroll and increase ram after some scrolls - ios

this is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"hourCell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=hoursarray[indexPath.row];
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
UIButton *buttonOff = [UIButton buttonWithType:UIButtonTypeCustom];
buttonOff.layer.cornerRadius = 5.0f;
UIButton *buttonT1 = [UIButton buttonWithType:UIButtonTypeCustom];
buttonT1.layer.cornerRadius = 5.0f;
UIButton *buttonT2 = [UIButton buttonWithType:UIButtonTypeCustom];
buttonT2.layer.cornerRadius = 5.0f;
buttonOff.frame = CGRectMake(130, 5, 40, 34);
[buttonOff setTitle:#"OFF" forState:UIControlStateNormal];
[buttonOff addTarget:self action:#selector(onButtonOFFTap:) forControlEvents:UIControlEventTouchUpInside];
buttonT1.frame = CGRectMake(190, 5, 40, 34);
[buttonT1 setTitle:#"T1" forState:UIControlStateNormal];
[buttonT1 addTarget:self action:#selector(onButtonT1Tap:) forControlEvents:UIControlEventTouchUpInside];
buttonT2.frame = CGRectMake(250, 5, 40, 34);
[buttonT2 setTitle:#"T2" forState:UIControlStateNormal];
[buttonT2 addTarget:self action:#selector(onButtonT2Tap:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:buttonOff];
[cell.contentView bringSubviewToFront:buttonOff];
buttonOff.tag=indexPath.row;
[cell addSubview:buttonT1];
[cell.contentView bringSubviewToFront:buttonT1];
buttonT1.tag=indexPath.row;
[cell.contentView bringSubviewToFront:buttonT2];
[cell addSubview:buttonT2];
buttonT2.tag=indexPath.row;
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"1"])
{
buttonOff.backgroundColor = [UIColor greenColor];
buttonT1.backgroundColor = [UIColor lightGrayColor];
buttonT2.backgroundColor = [UIColor lightGrayColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"2"])
{
buttonOff.backgroundColor = [UIColor lightGrayColor];
buttonT1.backgroundColor = [UIColor greenColor];
buttonT2.backgroundColor = [UIColor lightGrayColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"3"])
{
buttonOff.backgroundColor = [UIColor lightGrayColor];
buttonT1.backgroundColor = [UIColor lightGrayColor];
buttonT2.backgroundColor = [UIColor greenColor];
}
return cell;
}
The fact is that after two or three scrolls (fast and smooth) the scrolling goes slow and crappy and the ram used increase.
I tried to put if(cell==nill) but I'm using storyboard and the cell is never nill
Am I wrong in something?
Thanks a lot,
N.

There are a couple problems here.
The whole point of using dequeueReusableCellWithIdentifier: is to reuse your cells and their content. But I see you've used this line:
if ([cell.contentView subviews]){
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
to remove the cell content at every call to cellForRowAtIndexPath:. This is a waste of using dequeueReusableCellWithIdentifier:.
Nevertheless, your logic is almost correct. You can remove the subviews and create new subviews without having the incremental memory issues you're describing. The problem is you've made a small error:
You're adding the UIButtons directly to the cell's view, for example
[cell addSubview:buttonOff];
but removing the subviews of the cell's content view:
[cell.contentView subviews]
(You're also using bringSubviewToFront: ineffectively for this same reason.)
Because of this mistake, you're not actually removing the buttons at every call to cellForRowAtIndexPath: as you've intended so as you scroll back and forth, buttons are being added one on top of another on top of another, thus increasing memory usage.
To fix this problem, whether you add and remove from cell or cell.contentView, you have to be consistent.
All that aside though, since the content of your cells is very similar, I highly recommend you use dequeueReusableCellWithIdentifier: in the way it was intended by actually reusing your cells' content.

Thanks to all. This is the code working good. I added a TableViewCell class that contains only the outlet to the buttons (added buttons graphically in the storyboard):
#import <UIKit/UIKit.h>
#interface CHRTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UIButton *buttonOFF;
#property (weak, nonatomic) IBOutlet UIButton *buttonT1;
#property (weak, nonatomic) IBOutlet UIButton *buttonT2;
#end
then instantiated cell on tableview controller and pointing to the outlet changed the button's aspect:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CHRTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"hourCell" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text=hoursarray[indexPath.row];
cell.buttonOFF.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonOFF.layer.borderWidth = 0.5f;
cell.buttonOFF.layer.cornerRadius = 5.0f;
cell.buttonT1.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonT1.layer.borderWidth = 0.5f;
cell.buttonT1.layer.cornerRadius = 5.0f;
cell.buttonT2.layer.borderColor = [UIColor lightGrayColor].CGColor;
cell.buttonT2.layer.borderWidth = 0.5f;
cell.buttonT2.layer.cornerRadius = 5.0f;
[cell.buttonOFF setTitle:#"OFF" forState:UIControlStateNormal];
[cell.buttonOFF addTarget:self action:#selector(onButtonOFFTap:) forControlEvents:UIControlEventTouchUpInside];
[cell.buttonT1 setTitle:#"T1" forState:UIControlStateNormal];
[cell.buttonT1 addTarget:self action:#selector(onButtonT1Tap:) forControlEvents:UIControlEventTouchUpInside];
[cell.buttonT2 setTitle:#"T2" forState:UIControlStateNormal];
[cell.buttonT2 addTarget:self action:#selector(onButtonT2Tap:) forControlEvents:UIControlEventTouchUpInside];
cell.buttonOFF.tag=indexPath.row;
cell.buttonT1.tag=indexPath.row;
cell.buttonT2.tag=indexPath.row;
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"1"])
{
cell.buttonOFF.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];
cell.buttonT1.backgroundColor = [UIColor whiteColor];
cell.buttonT2.backgroundColor = [UIColor whiteColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"2"])
{
cell.buttonOFF.backgroundColor = [UIColor whiteColor];
cell.buttonT1.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];;
cell.buttonT2.backgroundColor = [UIColor whiteColor];
}
if([[NSString stringWithFormat:#"%#",[datiProgrTemp objectAtIndex:indexPath.row+48*day]] isEqual:#"3"])
{
cell.buttonOFF.backgroundColor = [UIColor whiteColor];
cell.buttonT1.backgroundColor = [UIColor whiteColor];
cell.buttonT2.backgroundColor = [UIColor colorWithRed:0.0f/255.0f green:200.0f/255.0f blue:60.0f/255.0f alpha:1.0f];;
}
return cell;
}

Related

How to create n number of UIButton programmatically in UITableView Cell?

I am trying to create one UITableView with n number of buttons depends on backend JSON data.
I have attached an image, i know how to create UIButtons on UITableViewCell but i don't know how to place them correctly inside UITableViewCell.
UIButton for UITableViewCell
UIButton *continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100, view1.frame.size.width-20, 40)];
[continuebtn setBackgroundColor:[UIColor grayColor]];
[continuebtn setTitle:#"Continue" forState:UIControlStateNormal];
continuebtn.layer.cornerRadius = 10;
continuebtn.layer.borderWidth =1.0;
continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
[continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
How to place 'n' number of UIButton on UITableViewCell ?? UIButton width depends on its text content
If you want to put buttons vertically in a cell, use following suggestions:
Your UITableviewCell's height would depend upon number of buttons. Implement heightForRowAtIndexPath method as following:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100.0f + (buttonsArray.count*buttonHeight+buttonsHeightSeparator);
//change 100.0f with height that is required for cell without buttons
//buttonHeight is a static float representing value for height of each button
//buttonHeightSeparator is a static float representing separation distance between two buttons
}
In your cellForRowAtIndexPath method, you can create buttons using following code:
for(int i=0; i<buttonsArray.count; i++) {
UIButton *continuebtn = [[UIButton alloc]initWithFrame:CGRectMake(10, 100+i*(buttonHeight+buttonsHeightSeparator), view1.frame.size.width-20, 40)];
[continuebtn setBackgroundColor:[UIColor grayColor]];
[continuebtn setTitle:#"Continue" forState:UIControlStateNormal];
continuebtn.layer.cornerRadius = 10;
continuebtn.layer.borderWidth =1.0;
continuebtn.layer.borderColor = [UIColor blackColor].CGColor;
[continuebtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[continuebtn addTarget:self action:#selector(continueBtnPressed:) forControlEvents:UIControlEventTouchUpInside]; //add target to receive button tap event
[continuebtn setTag:i]; //to identify button
[cell.contentView addSubview:continuebtn]; //add button to cell
}
I have found a better answer myself.
Please check this code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell addSubview:[self addView:indexPath.row]];
return cell;
}
-(UIView *)addView:(NSInteger)row{
UIView *progView;
progView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,cell.frame.size.width,cell.frame.size.height)];
progView.backgroundColor = [UIColor grayColor];
progView.tag = i;
progView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
int x,y;
x=10;y=10;
for(int i=0;i<10;i++){
UIButton *button = [[UIButton alloc]init];
NSString *myString=#"Dynamic";
[button setTitle:myString forState:UIControlStateNormal];
CGSize stringsize = [myString sizeWithFont:[UIFont systemFontOfSize:14]];
[button setFrame:CGRectMake(x,y,stringsize.width+40, stringsize.height+20)];
x+=stringsize.width+50;
NSLog(#"%d-%f",x,progView.frame.size.width);
if(x>progView.frame.size.width){
y+=50;
x=10;
}
button.layer.borderWidth =1.0;
button.layer.borderColor = [UIColor greenColor].CGColor;
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTag:i];
[progView addSubview:button];
}
return progView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 200;
}

UiTableViewHeader - Dynamic button event handler

I need to add a uiButton to a static uitableview section header - I've made an attempt with the following -
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}
-(void)receiverButtonClicked:(id)sender{
NSLog(#"button clicked");
}
the above adds a button - but doesn't react to the click event - can anyone suggest how I can get this to work?
UILabel does not handles touches by default.
Add following line of code:
customLabel.userInteractionsEnabled = YES;
In order to display button only for third section you should add following condition:
if(section == 2){...}
So your -tableView:viewForHeaderInSection: should look as follows:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection (NSInteger)section {
if(section != 2) return nil;
// you can get the title you statically defined in the storyboard
NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
CGRect frame = tableView.bounds;
// create and return a custom view
#define LABEL_PADDING 10.0f
HeaderLabelStyling *customLabel = [[HeaderLabelStyling alloc] initWithFrame:CGRectInset(frame, LABEL_PADDING, 0)] ;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
addButton.backgroundColor = [UIColor whiteColor];
addButton.titleLabel.textColor = [UIColor colorWithRed:240/255.0f green:118/255.0f blue:34/255.0f alpha:1.0f];
addButton.titleLabel.tintColor = [UIColor blackColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = #"iawn";
customLabel.text = sectionTitle;
customLabel.backgroundColor= [UIColor colorWithRed:143.0f/255.0f green:137.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
customLabel.userInteractionsEnabled = YES;
customLabel.textColor = [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f];
[customLabel addSubview:addButton];
[addButton addSubview:title];
[addButton addTarget:self action:#selector(receiverButtonClicked:) forControlEvents:UIControlEventTouchDown];
return customLabel;
}

IOS UITableview Scroll is not smooth in IOS6

And I complete IOS app in IOS 7 and its works fine IOS 7 and then I start converting my app to IOS 6 I face lot of problems.After a huge struggle I rectify almost all the issuse other that Performance issue
I am using UITableview to display all the contents and when I test my app in Iphone 5c there is no problem in scrolling the table view. And the I test my app in ipod retina list is not scrolling smoothly. It is one of the huge problem for me and also Its killing my time
To illustrate my issue I have added my tableview cell code below. Please Suggest me some quick solution
UITableviewCell Code
- (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.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
cell.selectionStyle = UITableViewCellEditingStyleNone;
UIView * contentview = [[[UIView alloc]init]autorelease];
UIImageView * userimage = [[[UIImageView alloc]init]autorelease];
UIImageView * itemimageview = [[[UIImageView alloc]init]autorelease];
UIView * bottomview = [[[UIView alloc]init]autorelease];
UILabel * imagenameLable = [[[UILabel alloc]init]autorelease];
UILabel * usernameLable = [[[UILabel alloc]init]autorelease];
UILabel * itemcostLable = [[[UILabel alloc]init]autorelease];
UIButton*fancybtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * addrditbtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UILabel * noofcommentsLable = [[[UILabel alloc]init]autorelease];
// [contentBgImageview setImage:[UIImage imageNamed:#"item_bg.png"]];
[itemimageview setAutoresizesSubviews:YES];
// [itemimageview setContentMode:UIViewContentModeScaleAspectFill];
[itemimageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"item_url_main_350"]]]];
[itemimageview setContentMode:UIViewContentModeScaleAspectFit];
[itemimageview setTag:indexPath.row];
[userimage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"user_url_main_70"]]]];
[bottomview setBackgroundColor:[UIColor colorWithRed:200/255 green:54/255 blue:54/255 alpha:0.4]];
[bottomview setBackgroundColor:[UIColor colorWithRed:255 green:255 blue:255 alpha:1]];
// [bottomview setAlpha:0.5];
[imagenameLable setText:[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"item_title"]];
[imagenameLable setTextColor:[UIColor blackColor]];
[imagenameLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[imagenameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:imagenameLable];
[usernameLable setText:[NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
[usernameLable setTextColor:[UIColor grayColor]];
[usernameLable setFont:[UIFont fontWithName:#"Helvetica" size:10]];
[usernameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:usernameLable];
[itemcostLable setText:[NSString stringWithFormat:#"%# %#",delegate.currencyStr,[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"price"]]];
[itemcostLable setTextColor:[UIColor grayColor]];
[itemcostLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
[itemcostLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:itemcostLable];
// [addrditbtn setImage:[UIImage imageNamed:#"add.png"] forState:UIControlStateNormal];
if ([[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"liked"]isEqualToString:#"No"])
{
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
else
{
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
NSString*itemid=[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"];
if ([delegate.fantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
if ([delegate.unfantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
fancybtn.tag=[itemid intValue];
[fancybtn addTarget:self action:#selector(fancyBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
addrditbtn.tag=[itemid intValue];
[addrditbtn addTarget:self action:#selector(addtolistBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[commentBtn setImage:[UIImage imageNamed:#"commentnew.png"] forState:UIControlStateNormal];
[commentBtn setUserInteractionEnabled:YES];
commentBtn.tag=indexPath.row;
[commentBtn addTarget:self action:#selector(commentBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIButton * usernameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[usernameBtn setUserInteractionEnabled:YES];
usernameBtn.tag=indexPath.row;
[usernameBtn addTarget:self action:#selector(usernameBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[noofcommentsLable setTextColor:[UIColor grayColor]];
[noofcommentsLable setFont:[UIFont fontWithName:#"Helvetica" size:12]];
int commentcount = 0;
if([delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]])
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue]+[[delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]]count];
}
else
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue];
}
[noofcommentsLable setText:[NSString stringWithFormat:#"%d",commentcount]];
UIScrollView * scroll = [[[UIScrollView alloc]init]autorelease];
// [scroll setScrollEnabled:NO];
[scroll setUserInteractionEnabled:YES];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureAction:)];
[recognizer setNumberOfTapsRequired:1];
scroll.userInteractionEnabled = YES;
[scroll addGestureRecognizer:recognizer];
[itemcostLable setTextAlignment:NSTextAlignmentRight];
[bottomview setFrame:CGRectMake(0,3,300,37)];
[itemimageview setFrame:CGRectMake(0,0,300,240)];
CGSize size;
if ([[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]!=[NSNull null]||[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]!=[NSNull null])
{
size= [self aspectScaledImageSizeForImageView:itemimageview width:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]floatValue] height:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]floatValue]];
}
else
{
size = CGSizeMake(100,100);
}
[itemimageview setFrame:CGRectMake((300-size.width)/2,0,size.width,size.height)];
[scroll setFrame:CGRectMake(0,43,300,size.height)];
//place holder image
UIImageView * placeholderimageview = [[[UIImageView alloc]init]autorelease];
[placeholderimageview setFrame:CGRectMake(130,0,40,size.height)];
[placeholderimageview setImage:[UIImage imageNamed:#"57.png"]];
[placeholderimageview setContentMode:UIViewContentModeScaleAspectFit];
// [itemimageview setBackgroundColor:[UIColor redColor]];
[imagenameLable setFrame:CGRectMake(40,5,160,15)];
[usernameLable setFrame:CGRectMake(40,20,160,15)];
[usernameBtn setFrame:CGRectMake(0,5,200,30)];
[itemcostLable setFrame:CGRectMake(220,0,70,40)];
[fancybtn setFrame:CGRectMake(5,size.height+48,78,25)];
[commentBtn setFrame:CGRectMake(221,size.height+48,40,25)];
[noofcommentsLable setFrame:CGRectMake(240,size.height+48,20,25)];
[addrditbtn setFrame:CGRectMake(265,size.height+48,27,25)];
// [commentBtn setFrame:CGRectMake(191,size.height+48,40,25)];
// [noofcommentsLable setFrame:CGRectMake(211,size.height+48,20,25)];
// [addrditbtn setFrame:CGRectMake(236,size.height+48,27,25)];
// [cartbtn setFrame:CGRectMake(268,size.height+48,27,25)];
[contentview setFrame:CGRectMake(10,5,300,size.height+78)];
[userimage setFrame:CGRectMake(5,5,30,30)];
[scroll setBackgroundColor:[UIColor colorWithRed:0.976 green:0.976 blue:0.976 alpha:1]];
[scroll setBackgroundColor:[UIColor clearColor]];
contentview.clipsToBounds = NO;
contentview.layer.masksToBounds = NO;
contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as you want.
[bottomview setBackgroundColor:[UIColor clearColor]];
userimage.layer.cornerRadius = 15.0;
userimage.layer.masksToBounds = YES;
[itemimageview setUserInteractionEnabled:YES];
[scroll setBackgroundColor:[UIColor clearColor]];
[bottomview setBackgroundColor:[UIColor clearColor]];
[contentview setBackgroundColor:[UIColor whiteColor]];
//place holder image
[contentview addSubview:scroll];
[scroll addSubview:placeholderimageview];
[scroll addSubview:itemimageview];
[contentview addSubview:bottomview];
[contentview addSubview:fancybtn];
[contentview addSubview:addrditbtn];
[contentview addSubview:commentBtn];
[contentview addSubview:noofcommentsLable];
[contentview addSubview:userimage];
[contentview addSubview:usernameLable];
[contentview addSubview:usernameBtn];
[cell.contentView addSubview:contentview];
[cell setBackgroundColor:[UIColor clearColor]];
[cell.contentView setBackgroundColor:[UIColor clearColor]];
// Configure the cell...
return cell;
}
Its because in every time when cellForRowAtIndexPath: method called you recreating all subviews again.
You must do it only once.
Make a class that inherits from UITableViewCell.
//MyCell.h file
#interface MyCell : UITableViewCell
//here declare all views that you need, e.g.
#property (strong, nonatomic) UILabel *imagenameLable;
#property (strong, nonatomic) UILabel *usernameLable;
// and so on. But only those, that you mast set value (or read values) outside of this class.
// the other views declare in MyClass.m file, so they are for private use (eg. contentview,etc...)
#end
//MyCell.m file
#interface MyCell()
// here declare private properties
#property (strong, nonatomic) UIView* contentview;
// and so on...
#end
#implementation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self setupUI];
}
return self;
}
- (void)setupUI
{
//and finally, in this method build your views, i.e. allocate your views, add subview of this cell, set frames, font to labels, text colors, etc...
//e.g.
self.contentview = [[[UIView alloc]init]autorelease];
self.contentview.clipsToBounds = NO;
self.contentview.layer.masksToBounds = NO;
self.contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
self.contentview.layer.shadowOffset = CGSizeMake(0,1);
self.contentview.layer.shadowOpacity = 0.2;
self.contentview.layer.shadowRadius = 0.6;
self.contentview.layer.cornerRadius = 6.0; // set as you want.
// initialize other views
[self.contentview addSubview:self.scroll];
[self.scroll addSubview:self.placeholderimageview];
[self.scroll addSubview:self.itemimageview];
[self.contentview addSubview:self.bottomview];
[self.contentview addSubview:self.fancybtn];
[self.contentview addSubview:self.addrditbtn];
[self.contentview addSubview:self.commentBtn];
[self.contentview addSubview:self.noofcommentsLable];
[self.contentview addSubview:self.userimage];
[self.contentview addSubview:self.usernameLable];
[self.contentview addSubview:self.usernameBtn];
[self.contentView addSubview:self.contentview];
// something like this.
}
#end
And finally
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell ==nil)
{
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier]autorelease];
}
// here set values to properties of your cell. EG set text, change color if needed, change frame if needed, etc... But not remove and add them again!
cell.usernameLable.text = [NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
//etc...
return cell;
}
I found the solution for my code
This is because of
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as
Once I remove this line from my code Its works fine
There is lot of optimalization issues in your code. You should use Instruments with Time Profiler template to detect bottlenecks.
BTW, When you draw shadow of CALayer you should set CALayer's shadowPath property for outline of the shadow. This will speed up drawing your shadow much. Please refer documentation for more details.
dialogContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:dialogContainer.bounds cornerRadius:dialogContainer.layer.cornerRadius].CGPath;

UITableview Cell Height is not calculated properly and cells overlap

I need to create and populate custom cells. These cells height are huge about 300-400.
So I have a populateCellView function , I call that function on heightForRowAtIndexPath to calculate height and in cellForRowAtIndexPath to add that view to cell content view, but somehow sometimes cells overlap.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self populateCellView:indexPath.row].frame.size.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIView *populateCell= nil;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
populateCell=[[UIView alloc] initWithFrame:CGRectZero];
[[populateCell layer] setBorderWidth:2.0f];
populateCell= [self populateCellView:indexPath.row];
[[cell contentView] addSubview:populateCell];
}
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
populate view function:
-(UIView *)populateCellView:(int)forCase
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width,500)];
[view setBackgroundColor:[UIColor colorWithRed:40/255.0 green:150/255.0 blue:213/255.0 alpha:1.0]];
view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
if ([view subviews]){
for (UIView *subview in [view subviews]) {
[subview removeFromSuperview];
}
}
UILabel *caseNumberLabel;
UILabel *caseNameLabel;
UILabel *caseSummaryLabel;
UILabel *caseAncLabel;
UILabel *caseNumberText;
UILabel *caseNameText;
UILabel *caseSummaryText;
UILabel *caseAncText;
//static label for case number
caseNumberLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,10,250, 50)];
caseNumberLabel.textColor = [UIColor whiteColor];
caseNumberLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNumberLabel.text =#"Case Number:";
caseNumberLabel.backgroundColor = [UIColor clearColor];
caseNumberLabel.numberOfLines=0;
caseNumberLabel.adjustsFontSizeToFitWidth = NO;
caseNumberLabel.tag=forCase;
caseNumberLabel.frame=[self calculateLabelFrame:caseNumberLabel];
//case number from plist
caseNumberText = [[UILabel alloc] initWithFrame:CGRectMake(caseNumberLabel.frame.size.width+50,caseNumberLabel.frame.origin.y,self.view.frame.size.width-caseNumberLabel.frame.size.width-50, 50)];
caseNumberText.textColor = [UIColor whiteColor];
caseNumberText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNumberText.text =[[self agenda] getCaseNumber:forCase];
caseNumberText.backgroundColor = [UIColor clearColor];
caseNumberText.numberOfLines=0;
caseNumberText.adjustsFontSizeToFitWidth = NO;
caseNumberText.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNumberText.frame=[self calculateLabelFrame:caseNumberText];
//static label for case name
caseNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNumberText.frame.origin.y + caseNumberText.bounds.size.height+5,250, 50)];
caseNameLabel.textColor =[UIColor whiteColor];
caseNameLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseNameLabel.text =#"Case Name:";
caseNameLabel.backgroundColor = [UIColor clearColor];
caseNameLabel.numberOfLines=0;
caseNameLabel.adjustsFontSizeToFitWidth = NO;
caseNameLabel.tag=forCase;
//[caseNumberLabel sizeToFit];
caseNameLabel.frame=[self calculateLabelFrame:caseNameLabel];
//case name from plist
caseNameText = [[UILabel alloc] initWithFrame:CGRectMake(caseNameLabel.frame.size.width+50,caseNameLabel.frame.origin.y,self.view.frame.size.width-caseNameLabel.frame.size.width-50, 50)];
caseNameText.textColor = [UIColor whiteColor];
caseNameText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseNameText.text =[[self agenda] getCaseName:forCase];
caseNameText.backgroundColor = [UIColor clearColor];
caseNameText.numberOfLines=0;
//caseNameText.adjustsFontSizeToFitWidth = NO;
caseNameText.tag=forCase;
[caseNameText sizeToFit];
//caseNameText.lineBreakMode = NSLineBreakByWordWrapping;
caseNameText.frame=[self calCellLabelFrame:caseNameText previousLabel:caseNameLabel];
//static label for case summary
caseSummaryLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseNameText.frame.origin.y + caseNameText.bounds.size.height+20,250, 50)];
caseSummaryLabel.textColor = [UIColor whiteColor];
caseSummaryLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseSummaryLabel.text =#"Case Summary:";
caseSummaryLabel.backgroundColor = [UIColor clearColor];
caseSummaryLabel.numberOfLines=0;
caseSummaryLabel.adjustsFontSizeToFitWidth = NO;
caseSummaryLabel.tag=forCase;
//[caseSummaryLabel sizeToFit];
caseSummaryLabel.frame=[self calculateLabelFrame:caseSummaryLabel];
//case name from plist
caseSummaryText = [[UILabel alloc] initWithFrame:CGRectMake(caseSummaryLabel.frame.size.width+50,caseSummaryLabel.frame.origin.y,self.view.frame.size.width-caseSummaryLabel.frame.size.width-100, 50)];
caseSummaryText.textColor = [UIColor whiteColor];
caseSummaryText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseSummaryText.text =[[self agenda] getCaseSummary:forCase];
caseSummaryText.backgroundColor = [UIColor clearColor];
caseSummaryText.numberOfLines=0;
//caseSummaryText.adjustsFontSizeToFitWidth = NO;
caseSummaryText.tag=forCase;
[caseSummaryText sizeToFit];
//caseSummaryText.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
caseSummaryText.frame=[self calCellLabelFrame:caseSummaryText previousLabel:caseSummaryLabel];
//static label for anc
caseAncLabel = [[UILabel alloc] initWithFrame:CGRectMake(50,caseSummaryText.frame.origin.y + caseSummaryText.bounds.size.height+15,250, 50)];
caseAncLabel.textColor = [UIColor whiteColor];
caseAncLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:24.0f];
caseAncLabel.text =#"ANC:";
caseAncLabel.backgroundColor = [UIColor clearColor];
caseAncLabel.numberOfLines=0;
caseAncLabel.adjustsFontSizeToFitWidth = NO;
caseAncLabel.tag=forCase;
//[ccaseAncLabel sizeToFit];
caseAncLabel.frame=[self calculateLabelFrame:caseAncLabel];
//case name from plist
caseAncText = [[UILabel alloc] initWithFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncLabel.frame.origin.y,self.view.frame.size.width-caseAncLabel.frame.size.width-50, 50)];
caseAncText.textColor = [UIColor whiteColor];
caseAncText.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:24.0f];
caseAncText.text =[[self agenda] getCaseAnc:forCase];
caseAncText.backgroundColor = [UIColor clearColor];
caseAncText.numberOfLines=0;
//caseAncText.adjustsFontSizeToFitWidth = NO;
caseAncText.tag=forCase;
[caseAncText sizeToFit];
//caseSummaryText.lineBreakMode = NSLineBreakByWordWrapping;
caseAncText.frame=[self calCellLabelFrame:caseAncText previousLabel:caseAncLabel];
//add button
UIButton *acceptButton=[UIButton buttonWithType:UIButtonTypeCustom];
[acceptButton setTag:forCase];
acceptButton.titleLabel.tag=1;
[acceptButton setFrame:CGRectMake(caseAncLabel.frame.size.width+50,caseAncText.frame.origin.y + caseAncText.bounds.size.height+20,181,39)];
NSString *radioButtonImage=#"view_attachment.png";
UIImage *acceptbuttonImage = [UIImage imageNamed:radioButtonImage];
[acceptButton setBackgroundImage:acceptbuttonImage forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(showAttachements:) forControlEvents:UIControlEventTouchUpInside];
//whie line
UIView *anotherline = [[UIView alloc] initWithFrame:CGRectMake(0, acceptButton.frame.origin.y + acceptButton.bounds.size.height+15, self.view.frame.size.width, 1)];
anotherline.backgroundColor=[UIColor whiteColor];
anotherline.tag=forCase;
[view addSubview:acceptButton];
[view addSubview: caseNumberLabel];
[view addSubview:caseNumberText];
[view addSubview:caseNameLabel];
[view addSubview:caseNameText];
[view addSubview:caseSummaryLabel];
[view addSubview:caseSummaryText];
[view addSubview:caseAncText];
[view addSubview:caseAncLabel];
[view addSubview:anotherline];
view.frame = CGRectMake(0,0, self.view.frame.size.width,anotherline.frame.origin.y + anotherline.bounds.size.height+5);
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
return view;
}
I call reload data like this
dispatch_async(dispatch_get_main_queue(), ^{
[_agenda loadFromPlist];
[[self tableView] reloadData];
});
Any idea why cells overlaps?
Its your UITableview cellforIndexPath causing overlap
try this
if (!populateCell){
populateCell = (UIView*)[cell viewWithTag:1];
populateCell= [self populateCellView:indexPath.row];
if ([[cell contentView] subviews]){
for (UIView *subview in [[cell contentView] subviews]) {
[subview removeFromSuperview];
}
}
[[cell contentView] addSubview:populateCell];
}
cell.backgroundColor=[UIColor clearColor];
At the end of the UITableViewDataSource method, tableView:cellForRowAtIndexPath:, you have to call [[cell contentView] addSubView:populateCell]. If the table dequeued a cell successfully, you have to retrieve the appropriate populateCell and add it to the contentView.
If you use storyboards, and set a different height for the cells, and the rows in the tableview, the height will usually overlap. The other answers are also highly valid, but usually when I've encountered this problem, the bug lies in a different value on row height and cell height in the tableview object in your storyboard...

UITableView separator line does not show in iPhone app

I have app in which i am using tableView problem is that when tableView has one record then it does not show separator line but shows when there are two records.
The first cell in tableView is textField. here is the code i am using.
for (UIView *subView in cell.subviews)
{
if (subView.tag == 2 || subView.tag == 22)
{
[subView removeFromSuperview];
}
}
tableView.backgroundView=nil;
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.separatorInset = UIEdgeInsetsZero;
if(indexPath.section==0){
tagInputField =[[UITextField alloc]initWithFrame:CGRectMake(0,0,248,31)];
tagInputField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
tagInputField.textAlignment=UITextAlignmentLeft;
tagInputField.backgroundColor=[UIColor whiteColor];
tagInputField.tag = 2;
tagInputField.delegate = self;
tagInputField.clearButtonMode = UITextFieldViewModeWhileEditing;
[tagInputField.layer setCornerRadius:5.0f];
[tagInputField.layer setMasksToBounds:YES];
tagInputField.layer.borderWidth = 0.3;
tagInputField.layer.borderColor = [UIColor darkGrayColor].CGColor;
tagInputField.font=[UIFont fontWithName:#"Myriad-Pro" size:8];
[tagInputField setText:#"Enter tag here "];
tagInputField.textColor =[UIColor grayColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
[cell addSubview:tagInputField];
return cell;
}
if(indexPath.section==1) {
UIButton *crossButton =[[UIButton alloc]initWithFrame:CGRectMake(228, 8, 18, 18)];
crossButton.tag = 22; //use a tag value that is not used for any other subview
//crossButton.backgroundColor = [UIColor purpleColor];
crossButton.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"Cross.png"]];
[cell addSubview:crossButton];
cell.textLabel.font =[UIFont fontWithName:#"Myriad-Pro" size:8];
cell.textLabel.textColor =[UIColor grayColor];
cell.backgroundColor=[UIColor whiteColor];
cell.textLabel.text =[tagArray objectAtIndex:indexPath.row];
[crossButton addTarget:self action:#selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];
[tagInputField setFrame:CGRectMake(5,0,248,31)];
tableView.backgroundColor=[UIColor whiteColor];
[tagInputField.layer setCornerRadius:0.0f];
[tagInputField.layer setMasksToBounds:YES];
tagInputField.layer.borderWidth = 0.0;
tagInputField.layer.borderColor = [UIColor clearColor].CGColor;
return cell;
}
When you will have only 1 record then separator will not show, and you should setting the separator for tableView at viewDidLoad look like
- (void)viewDidLoad
{
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
and in any case you want to show your own separator for every single cell ten try to add a imageView or somrthing witch share by the table cell
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];
How to customize tableView separator in iPhone
go for more on it....
Just try like this in side the Cell_for_Row_At_Index_path delegate method:
[tableView setSeparatorInset:UIEdgeInsetsZero];
[tableView setSeparatorColor:[UIColor greenColor]];
just paste this line and check.
add an empty footer at the end of the tableview to show the separator. To do so implement the following tableview delegate method in your class with your other tableview delegate functions:
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0.001;
}
I used this to add last cell separator line....
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 1.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
// To "clear" the footer view
UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorLine.layer.borderColor = [UIColor grayColor].CGColor;
separatorLine.layer.borderWidth = 1.0;
return separatorLine;
}
I found none of the above answers worked. I was particularly wary of the answer suggesting adding a UIView to look like the line.
In the end I found that this answer worked for me:
tableView.separatorStyle= UITableViewCellSeparatorStyleSingleLine;
In another answer it was suggested that adding worked better
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
tableView.separatorStyle= UITableViewCellSeparatorStyleSingleLine;
but I found that this was unnecessary.
All the credit goes to user859045 and samvermette for their answers on different threads. samvermette's thread especially has a lot of answers on this topic which are very helpful and worth a look.

Resources