I have a list of contacts, app can add/view details. I added a star button in my custom UITableViewCell, It is for "Favorites" functionality. I want my button to be color yellow if the contact is 'Favorited' and Gray if not. Here is my code.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
forIndexPath:indexPath];
ContactUtilities *cu = [[ContactUtilities alloc]init];
NSMutableDictionary *listToUse = [NSMutableDictionary new];
if([self.txtSearchContacts.text isEqualToString:#""]){
listToUse = self.contactList;
} else {
listToUse = searchContactList;
}
NSArray *keyList = [listToUse allKeys];
NSString *search = [keyList objectAtIndex:indexPath.row];
Contact *contact = [[Contact alloc]init];
contact = [cu searchContact:search :listToUse];
//Tagging
UILabel *lblContactName = [cell.contentView viewWithTag:ContactCellElementName];
UIImageView *imgContactPic = [cell.contentView viewWithTag:ContactCellElementImage];
UILabel *lblContactCompany = [cell.contentView viewWithTag:ContactCellElementCompany];
UILabel *lblContactNumber = [cell.contentView viewWithTag:ContactCellElementNumber];
UIButton *isFavorite = (UIButton *)[cell viewWithTag:ContactCellElementButton];
UIImage* image = [UIImage imageNamed:contact.imageName];
CGImageRef cgref = [image CGImage];
CIImage *cim = [image CIImage];
if (cim == nil && cgref == NULL)
{
image = [UIImage imageNamed:#"Person"];
}
lblContactName.text = contact.contactName;
imgContactPic.image = image;
lblContactCompany.text = contact.contactCompanyName;
lblContactNumber.text = contact.contactPhoneNumber;
//This is where it doesn't work..
if([contact.isFavorite isEqualToString:#"YES"]){
[isFavorite setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
} else {
[isFavorite setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
}
//I also have a property that will check if you will show the button. This is working already.
if([contact.shouldShow isEqualToString:#"No"]){
[isFavorite removeFromSuperview];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
That is my cellForRowAtIndexPath code. I am currently trying the setTitleColor property but it doesn't work. Same as the setTintColor it doesn't work either.
Tint color is what you want, but it only works if the image is a PNG with an alpha channel, and the rendering mode of the image is set to template. Refer to this answer. If you're assigning the image to the button in a storyboard, you can set the rendering mode in the asset library.
Related
I have a tableview whose rows are dynamic and each row have n numbers of imageviews as it is in the screenshot attached
Now what I want is to know which imageview I have clicked.
NOTE : imageview is added dynamically to one view and that view is added to scrollview so that it can scroll horizontally.
And there are n numbers of row in a tableview.
EDIT:
I tried adding simple button as well above the image view just to try out if that clicks but its click also didn't work.
I tried the solution of Gesture as well but that also didn't work
CODE:
-(UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strrowId ;
UITableViewCell *cell = [_tblviewScroll1 dequeueReusableCellWithIdentifier:#"cellOne"];
// create and add labels to the contentView
[cell.contentView setBackgroundColor:[UIColor colorWithRed:231.0/255.0 green:231.0/255.0 blue:231.0/255.0 alpha:1.0]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// cell.contentView.userInteractionEnabled=NO;
scrollView1 = (UIScrollView*)[cell.contentView viewWithTag:3];
[scrollView1 setShowsVerticalScrollIndicator:NO];
scrollView1.delegate = self;
NSArray* subviews1 = [scrollView1 subviews];
for (UIView* subview in subviews1) {
[subview removeFromSuperview];
}
if (scrollView1.contentOffset.y > 0 || scrollView1.contentOffset.y < 0 )
scrollView1.contentOffset = CGPointMake(scrollView1.contentOffset.x, 0);
[scrollView1 setBackgroundColor:[UIColor colorWithRed:231.0/255.0 green:231.0/255.0 blue:231.0/255.0 alpha:1.0]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleBlack;
scrollView1.clipsToBounds = YES
scrollView1.scrollEnabled = YES;
for (int i = 0; i <mutSubTitle.count; i++)
{
NSString *ids = #"";
UIView *viewvertically1;
viewvertically1=[[UIView alloc]init];
viewvertically1.tag = (i+1);
[viewvertically1 setUserInteractionEnabled:YES];
[viewvertically1 setBackgroundColor:[UIColor whiteColor]];
//Displaying image
NSString *strImgUrl = #"https://img.xxxx.com/";
NSString *strimge=[mutSubImag objectAtIndex:i];
strImgUrl = [strImgUrl stringByAppendingString:strimge];
NSURL *url = strImgUrl;
UIImage *image = [UIImage imageNamed:url];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame= CGRectMake(0, 10, 170, 110);
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[imageView setUserInteractionEnabled:YES];
// images with Lazy Loading
[imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:#"Placeholder.png"]];
UITapGestureRecognizer *imgTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureTapEvent:)];
imgTapGesture.numberOfTouchesRequired = 1;
[imageView addGestureRecognizer:imgTapGesture];
[viewvertically1 addSubview:imageView];
[viewvertically1 addSubview:lblDesc];
[scrollView1 addSubview:viewvertically1];
//[cell bringSubviewToFront:scrollView1];
}
return cell;
}
In your cellForRowAtIndexPath method add the UITapGestureRecognizer for your Concept
// by default the imageview userInteraction is disable you need to manually enable
cell.yourimageView.userInteractionEnabled = YES;
// the following line used for assign the different tags for eachImage
cell.yourimageView.tag = indexPath.row;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(ImageTapped:)];
tap.numberOfTapsRequired = 1;
[cell.yourimageView addGestureRecognizer:tap];
finally need to check which imageView was clicked, check the flag in selector method
-(void)ImageTapped :(UITapGestureRecognizer *) gesture
{
// you can get tag in which image is selected
NSLog(#"Tag = %d", gesture.view.tag);
}
Try giving a button instead of image view added to a view. Assign the image to button's backgroundImageView. You can then give actions for the buttons
Use UIButton as #Arun says or the imageview ur using currently add button on Image with clear background color and add tag to that button and use that click action.
I'm getting some really unusual behavior with my application. I have a tableview that loads cells based on data from a server, The data coming from the server is great, no duplicates and is how it should be. However as I scroll through my table I'm noticing UIButtons that I use setTitle on are showing duplicate title that were previously shown while scrolling, as if the reused cells aren't updating the title in some cases when setTitle is called..
UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
NSDictionary *tag = [self.tags objectAtIndex:indexPath.row];
ArgumentButton *nameButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_NAME];
[nameButton addTarget:self action:#selector(tagSelected:) forControlEvents:UIControlEventTouchUpInside];
[nameButton setTitle:[NSString stringWithFormat:#"#%#", [tag objectForKey:#"tag"]] forState:UIControlStateNormal];
nameButton.argument = [tag objectForKey:#"tag"];
UILabel *totalFollowersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_FOLLOWERS];
totalFollowersLabel.text = [tag objectForKey:#"followers"];
UILabel *followersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOWERS];
UIView *dividerView = (UIView *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_DIVIDER];
UILabel *totalProductsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_PRODUCTS];
totalProductsLabel.text = [tag objectForKey:#"products"];
UILabel *productsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_PRODUCTS];
if (self.allowFollow) {
totalFollowersLabel.frame = CGRectMake(30, totalFollowersLabel.frame.origin.y, totalFollowersLabel.frame.size.width, totalFollowersLabel.frame.size.height);
followersLabel.frame = CGRectMake(30, followersLabel.frame.origin.y, followersLabel.frame.size.width, followersLabel.frame.size.height);
dividerView.frame = CGRectMake(133, dividerView.frame.origin.y, dividerView.frame.size.width, dividerView.frame.size.height);
totalProductsLabel.frame = CGRectMake(157, totalProductsLabel.frame.origin.y, totalProductsLabel.frame.size.width, totalProductsLabel.frame.size.height);
productsLabel.frame = CGRectMake(157, productsLabel.frame.origin.y, productsLabel.frame.size.width, productsLabel.frame.size.height);
NSString *followButtonTitle = ([[tag objectForKey:#"followed"] isEqualToString:#"1"]) ? #"Unfollow" : #"Follow";
ArgumentButton *followButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOW];
followButton.argument = indexPath;
[followButton addTarget:self action:#selector(followSelected:) forControlEvents:UIControlEventTouchUpInside];
[followButton setTitle:followButtonTitle forState:UIControlStateNormal];
followButton.hidden = NO;
}
HorizontalScroll *scroll = (HorizontalScroll *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_SCROLL];
scroll.contentOffset = CGPointMake(-5, 0);
scroll.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
scroll.pagingEnabled = NO;
[scroll resetItems];
NSArray *items = [tag objectForKey:#"items"];
NSMutableArray *scrollItems = [[NSMutableArray alloc] init];
for (NSDictionary *item in items) {
NSArray *scrollItemXIB = [[NSBundle mainBundle] loadNibNamed:#"DetailedFeedScrollItemView" owner:self options:nil];
UIView *scrollItemView = [scrollItemXIB lastObject];
ArgumentButton *itemButton = (ArgumentButton *)[scrollItemView viewWithTag:DETAILED_FEED_SCROLL_ITEM_TAG_BUTTON];
[itemButton sd_setImageWithURL:[APIController resourceUrlForUserId:[item objectForKey:#"userId"] resourceName:[item objectForKey:#"thumbnail"]] forState:UIControlStateNormal];
[itemButton addTarget:self action:#selector(productSelected:) forControlEvents:UIControlEventTouchUpInside];
itemButton.argument = [item objectForKey:#"id"];
[scrollItems addObject:scrollItemView];
}
[scroll loadItems:scrollItems];
return cell;
Note: I am using UITableViewCells within their own XIB for this, which is set like this in viewDidLoad.
[self registerNib:[UINib nibWithNibName:#"DetailedTagsFeedTableViewCell" bundle:nil] forCellReuseIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
It's as if [nameButton setTitle:] is not setting the right titles while scrolling? I've tried a little debugging by setting the followersLabel text equal to the same value that we're attempting to set with setTitle on the nameButton, and the value IS correct when setting the .text property of the label in the same cell.. Very confusing.
The Argument button class is nothing special. Just a simple subclass that has a public property for passing an argument with itself to a target/action.
I would like to use a UITextField to enter text into a UITextField instead of UIPickerView using the UITextField .tag
The view is quite complex and consists of several views which I will explain.
htmlContainerScrollView, contains multiple
- axisContainerScrollView, contains multiple
- itemField
UITableView - used to pass text into itemField
So with that in mind, this is how I set up my htmlContainerScrollView. I have added comments to explaine what I am trying to achive.
- (void) displayViews {
// add scrollview, This view is ued to hold all of the axis (vertical scrolling only)
htmlContainerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 44.0, self.view.frame.size.width, 309.0)];
//TODO: replace this array with a dynamic implementation of the axis images. Will need someone to design the images for me
imagesArray = [NSArray arrayWithObjects:[UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], [UIImage imageNamed:#"LPA.png"], [UIImage imageNamed:#"LPB.png"], [UIImage imageNamed:#"LPC.png"], [UIImage imageNamed:#"LPD.png"], nil];
// Loop creates each axis
tagNumber = 1; // init the tagNumver starting from 1
for(int i = 0; i< axisNo; i++) {
CGFloat y = i * 77; // places each axis 77pxl below the previous
int itemsForRow = [itemsArray[i] intValue]; // get the current number of items for this axis
int scrollWidth = (itemsForRow * 40)+4; // calculate scroll width using the umber of items for this axis * by the size of each item.textfield
// create axis scroll view (horizontal scrolling only)
UIScrollView *axisContainerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, y,self.view.frame.size.width, 77.0)]; //device view width etc.
axisContainerScrollView.contentSize = CGSizeMake(scrollWidth, 77.0); // axis.view scrollable width
axisContainerScrollView.backgroundColor = [UIColor whiteColor];
[htmlContainerScrollView addSubview:axisContainerScrollView];
// make sure the view goes right to the edge of the screen.
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0.0, 0.0, scrollWidth+10, 77.0);
//grey header for each cell, if the total number of items exceeds the width of the device view then make the header the correct size
if(scrollWidth > self.view.frame.size.width) {
topBorder = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, scrollWidth, 18.0)];
topBorder.backgroundColor = [UIColor colorWithRed:colorController.fbRed/255.0 green:colorController.fbGreen/255.0 blue:colorController.fbBlue/255.0 alpha:1.0];
} else {
topBorder = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 18.0)];
topBorder.backgroundColor = [UIColor colorWithRed:colorController.fbRed/255.0 green:colorController.fbGreen/255.0 blue:colorController.fbBlue/255.0 alpha:1.0];
}
[axisContainerScrollView addSubview:topBorder];
[axisContainerScrollView addSubview:view];
int itemsCount = [itemsArray[i] intValue];
// add axis image to each scrollview (i.e. a, b, c, d, e, f, g etc.)
UIImageView *currentAxisImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, y, 18.0, 18.0)];
currentAxisImage.image = imagesArray[i];
[htmlContainerScrollView insertSubview:currentAxisImage aboveSubview:view];
// loop creates each item for current axis
for (int i = 0; i < itemsCount; i++) {
// create header for itemField
itemHeaderLabel = [[UILabel alloc] initWithFrame:CGRectMake((i*40)+2, 20, 40, 15)];
itemHeaderLabel.backgroundColor = [UIColor colorWithRed:colorController.grRed/255.0 green:colorController.grGreen/255.0 blue:colorController.grBlue/255.0 alpha:1.0];
[itemHeaderLabel setTextAlignment:NSTextAlignmentCenter];
itemHeaderLabel.font = [UIFont fontWithName:#"Helvetica" size:14];
itemHeaderLabel.textColor = [UIColor whiteColor];
NSString *strFromInt = [NSString stringWithFormat:#"%d",i+1]; // start from 1 not 0
itemHeaderLabel.text = strFromInt;
[view addSubview:itemHeaderLabel];
// itemField is the UITextField I would like to add text too from UITableViewCell selections
itemField = [[UITextField alloc] initWithFrame:CGRectMake((i*40)+2, 35, 40, 40)];
itemField.delegate = self; // set delegate so you can use UITextField delegate methods
itemField.textColor = [UIColor blackColor];
[itemField setTextAlignment:NSTextAlignmentCenter];
itemField.font = [UIFont fontWithName:#"Helvetica" size:20];
itemField.backgroundColor=[UIColor whiteColor];
itemField.layer.borderColor = [[UIColor colorWithRed:colorController.grRed/255.0 green:colorController.grGreen/255.0 blue:colorController.grBlue/255.0 alpha:1.0] CGColor];
itemField.layer.borderWidth = 0.5f;
[view addSubview:itemField];
itemField.tag = tagNumber; // set tag
tagNumber ++;
[columnArrayOfTextFields addObject:itemField]; // array of items textfields.. not using this currently but might become usefull in the future. (legacey code)
}
[rowArrayOfTextFields addObject:columnArrayOfTextFields]; // array of arrays.. not using this currently but might become usefull in the future. (legacey code)
}
// exit loop, set first reasponder to the first itemField.
[itemField viewWithTag:1];
[itemField becomeFirstResponder];
// add the whole scrollview to the mainview.
htmlContainerScrollView.contentSize = CGSizeMake(self.view.frame.size.width, 77 *axisNo);
[self.view addSubview:htmlContainerScrollView];
}
So at this point I have created the view and assigned each itemField a unique tag value. Now I will show you my didSelectRowAtIndexPath which is not complete, I think this is where I should set the text using the UITextFieldDelegates but I am not sure how.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
itemField.text = selectedCell.textLabel.text; // dose not work.. dosnt call UITextfield delegates or anything
[tableView deselectRowAtIndexPath:indexPath animated:YES]; //turns the UITableViewCell button as apposed to a single press fielf
}
and finally these are my UITextFieldDelegates.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
itemField.text = textField.text;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
return NO; // Hide keyboard so that you can use the UITableView selections to populate the UITextfeild itemField
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
currentSelected.text = textField.text;
NSInteger nextTag = currentSelected.tag + 1;
// Set next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// probably dont need this if I am not showing the UIkeyboard
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
You should create a custom tableview cell which has a uitextfield in it. This way you can easily set its delegate to self in cellForRowAtIndexPath like this:
- (UITableViewCell *)tableView:(UITableView *)view cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCellWithTextField* cell = .. //create cell
cell.textField.delegate = self;
return cell;
}
If you don't want to put it in tableview, fix this:
[itemField viewWithTag:1];
[itemField becomeFirstResponder];
should be:
itemField = [view viewWithTag:1];
[itemField becomeFirstResponder];
The problem I encounter is that whenever a row goes out of view, the scroll has a very fast and short lag.
This is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)_collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [self.collView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
Saints *note = nil;
int aX=0;
int aY=0;
note = [self.fetchedResultsController objectAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if([view isKindOfClass:[UIImageView class]])
{
[view removeFromSuperview];
}
else if([view isKindOfClass:[UILabel class]])
{
[view removeFromSuperview];
}}
cell.backgroundColor = [UIColor clearColor];
UIImage *imgbackground = [UIImage imageNamed:#"today-left-side-images-bg.png"];
NSArray *messages = [[NSArray alloc] initWithObjects: #"random-saint-text-bg-brown.png",#"random-saint-text-bg-brightblue.png",#"random-saint-text-bg-green.png",#"random-saint-text-bg-grey.png",#"random-saint-text-bg-lightblue.png",#"random-saint-text-bg-lime.png",#"random-saint-text-bg-purple.png",#"random-saint-text-bg-red.png",#"random-saint-text-bg-teal.png",nil];
int randNum = arc4random() % [messages count];
NSString *returnValue = [messages objectAtIndex:randNum];
NSString *rndBGImg= returnValue;
UIImage *imgbackgroundlower = [UIImage imageNamed:rndBGImg];
UIImageView *imgViewlower = [[UIImageView alloc] initWithImage:imgbackgroundlower];
//imgViewlower.frame=CGRectMake(aX, aY+140, 140,73);
imgViewlower.frame=CGRectMake(aX+4, aY+114, 119,43);
UIImageView *imgView = [[UIImageView alloc] initWithImage:imgbackground];
imgView.frame=CGRectMake(aX, aY, 127,162);
UIImageView *imgSaintPic = [[UIImageView alloc]init];
imgSaintPic.tag=1;
imgSaintPic.frame=CGRectMake(aX+6, aY+6, 114,145);
//NSString *imgname = [aDic objectForKey:#"saint_image"];
NSString *imgname = note.saint_imagethumbnail;
UIImage *tempimg= [UIImage imageNamed:imgname];
[imgSaintPic setImage:tempimg];
UILabel *lblNamelocal=[[UILabel alloc]init];
NSString *strSaintName=note.saint_name;
//lblNamelocal.text=strSaintName;
if([note.saint_title length]>1)
lblNamelocal.text=[NSString stringWithFormat:#"%# %#",note.saint_title,strSaintName];
else
lblNamelocal.text=[NSString stringWithFormat:#"%#",strSaintName];
//lblNamelocal.frame = CGRectMake(aX+6, aY+109, 116,30);
[lblNamelocal sizeToFit];
lblNamelocal.frame = CGRectMake(aX+5, aY+115, 118,26);
lblNamelocal.lineBreakMode = UILineBreakModeWordWrap;
lblNamelocal.numberOfLines = 0;
lblNamelocal.backgroundColor = [UIColor clearColor];
lblNamelocal.textColor = [UIColor whiteColor];
lblNamelocal.font = [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:11 ];
// lblNamelocal.textAlignment=UITextAlignmentLeft;
lblNamelocal.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
lblNamelocal.shadowColor = [UIColor darkGrayColor];
lblNamelocal.shadowOffset = CGSizeMake(0,0.5);
lblNamelocal.textAlignment = UITextAlignmentCenter;
UILabel *lblsubtitle=[[UILabel alloc]init];
//NSString *strSaintSubtitle=[aDic objectForKey:#"saint_title"];
lblsubtitle.text=note.saint_subtitle;
//lblsubtitle.frame = CGRectMake(aX+6, aY+132, 116, 25);
lblsubtitle.frame = CGRectMake(aX+5, aY+140, 113, 20);
lblsubtitle.lineBreakMode = UILineBreakModeWordWrap;
lblsubtitle.numberOfLines = 2;
lblsubtitle.backgroundColor = [UIColor clearColor];
lblsubtitle.textColor = [UIColor whiteColor];
lblsubtitle.font = [UIFont fontWithName:#"HelveticaNeue" size:10];
// Removed CJamesRun lblsubtitle.textAlignment=UITextAlignmentLeft;
lblsubtitle.shadowColor = [UIColor darkGrayColor];
lblsubtitle.shadowOffset = CGSizeMake(0,0.5);
lblsubtitle.textAlignment = UITextAlignmentCenter;
imgViewlower.tag=3;
lblNamelocal.tag=2;
lblsubtitle.tag=4;
[cell.contentView addSubview:imgView];
[cell.contentView addSubview:imgSaintPic];
[cell.contentView addSubview:imgViewlower];
[cell.contentView addSubview:lblNamelocal];
[cell.contentView addSubview:lblsubtitle];
// cell.layer.masksToBounds = NO;
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
What I've tired is to rasterize the cell layer, and also to remove the views from the SuperView upon creating a new cell.
Any other suggestions?
I would recommend setting up your cells' subviews just once, and then only updating the contents inside collectionView:cellForItemAtIndexPath:. E.g. you're loading some images in each cell, but those are the same for every cell, so loading them every time the cell is reused is unnecessary.
I have one table view in that cell is custom. I am adding two button on each cell of table view. when I click on first button at same time second button from same cell is changing its image. for that I have methods as editQuantity and Cancelorder. using #sel. I am getting an issue that when i click on first button insted of changing same cell another button its changing another cells button also when I scroll table view its losses all selected button
Here Is My Code--
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
simpleTableIdentifier = #"MenuNameCell";
MenuNameCell *cell = (MenuNameCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell== nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MenuNameCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
NSLog(#"---------new cell agin");
}
else
{
NSArray *arrayView = [cell.contentView subviews];
for (UIView *vTemp in arrayView)
{
[vTemp removeFromSuperview];
}
NSLog(#"---No New Cell hiiii");
// Setting Tag To UIButton
_checkButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
_cancelButton = (UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
// Creating Label Menu Name
_nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 11, 82, 21)];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.text = [_hotel._orderedMenus objectAtIndex:indexPath.row];
// Creating Label Menu Cost
_amountMenu = [[UILabel alloc] initWithFrame:CGRectMake(167, 13, 44, 21)];
_amountMenu.backgroundColor = [UIColor clearColor];
_amountMenu.text = [[_hotel._menuPrices objectAtIndex:indexPath.row] stringValue];
// Creating Text Field For Order Quantity
_textFieldQuantity = [[UITextField alloc] initWithFrame:CGRectMake(125,14,42,21)];
_textFieldQuantity.userInteractionEnabled = NO;
_textFieldQuantity.text = [[_hotel._selectedQuantity objectAtIndex:indexPath.row] stringValue];
// Creating Button For Check Order
_checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_checkButton setFrame:CGRectMake(232, 13, 25, 28)];
[_checkButton setTag:indexPath.row];
_checkButton.titleLabel.tag = indexPath.row;
[_checkButton setBackgroundImage:[UIImage imageNamed:#"edit.png"]forState:UIControlStateNormal];
[_checkButton addTarget:self action:#selector(editQuantity:) forControlEvents:UIControlEventTouchUpInside];
// Creating Button For CANCEL Order
_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[_cancelButton setFrame:CGRectMake(265, 13, 25, 28)];
[_cancelButton setBackgroundImage:[UIImage imageNamed:#"cancel.png"] forState:UIControlStateNormal];
[_cancelButton setTag:indexPath.row];
_cancelButton.titleLabel.tag = indexPath.row;
[_cancelButton addTarget:self action:#selector(cancelOreder:) forControlEvents:UIControlEventTouchUpInside];
// Adding All To Content View
[cell.contentView addSubview:_nameLabel];
[cell.contentView addSubview:_amountMenu];
[cell.contentView addSubview:_textFieldQuantity];
[cell.contentView addSubview:_checkButton];
[cell.contentView addSubview:_cancelButton];
//objc_setAssociatedObject(_checkButton, iindex, indexPath,OBJC_ASSOCIATION_RETAIN );
return cell;
}
-(void)editQuantity:(id)sender{
button = (UIButton *)sender;
row = button.tag;
col = button.titleLabel.tag;
NSLog(#"Check Button index is %d",row);
NSLog(#"cehck title is %d",col);
_textFieldQuantity.userInteractionEnabled = YES;
UIImage *buttonImage = [UIImage imageNamed:#"edit_over.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
UIImage *buttonImageCancel = [UIImage imageNamed:#"check.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
_cancelButton.tag = 0;
}
-(void)cancelOreder:(id)sender{
button = (UIButton *)sender;
row = button.tag;
NSLog(#"The Row Selected iS At Cancel Order ISSSS----%d", row);
if (_cancelButton.tag == 0){
_textFieldQuantity.userInteractionEnabled = NO;
UIImage *buttonImageCancel = [UIImage imageNamed:#"check_over.png"];
[_cancelButton setBackgroundImage:buttonImageCancel forState:UIControlStateNormal];
UIImage *buttonImageCancel1 = [UIImage imageNamed:#"cancel.png"];
[_cancelButton setBackgroundImage:buttonImageCancel1 forState:UIControlStateNormal];
UIImage *buttonImage = [UIImage imageNamed:#"edit.png"];
[_checkButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
_cancelButton.tag = 1;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"iHomeDelivery" message:#"Do You Want To Cancel the Order" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
The problem is that the default tag value for any control is set to 0 and you have used the _cancelButton.tag = 0;. Just change the value to 10 and then _cancelButton.tag = 1; change 1 to 11.
This will solve your problem :)
As I see _checkButton, _nameLabel, _amountMenu, _textFieldQuantity & _cancelButton all are instance variable of your view controller class.
In cellForRowAtIndexPath: as you are assigning new objects to all these, they will refere to objects of last cell displayed. Means all these will point to components from last cell.
Hence changing background images for _checkButton & _cancelButton will affect for buttons in last cell.
Also in cellForRowAtIndexPath: while creating these buttons, you are setting background image for them, hence after scrolling your button images are getting changed. Remember cellForRowAtIndexPath: gets called for a row each time that row becomes visible after getting hidden while scrolling.
You need to maintain state of buttons in separate array, so that you can reset state for buttons in cellForRowAtIndexPath: after dequeuing.