I have tried to show a custom view with an accept button and decline button (as subviews) in a table view cell. I have the following code implemented:
tableView: cellForRowAtIndexPath: method
...
if ([status isEqualToString:#"pending"] || [status isEqualToString:#"declined"]){
cell.accessoryView = [self setAccessoryViewForCell:cell];
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
...
- (UIView *)setAccessoryViewForCell:(UITableViewCell *)cell
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(192, 0, 128, 44)];
UIButton *acceptButton = [[UIButton alloc] initWithFrame:CGRectMake(2, 5, 60, 34)];
UIButton *declineButton = [[UIButton alloc] initWithFrame:CGRectMake(66, 5, 60, 34)];
[acceptButton setTitle:#"A" forState:UIControlStateNormal];
[declineButton setTitle:#"D" forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(acceptButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[declineButton addTarget:self action:#selector(declineButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:acceptButton];
[view addSubview:declineButton];
return view;
}
I have tried to debug it, but the methods are called appropriately.
Finally, the problem was not in the cellForRowAtIndexPath: method, but in the setAccessoryViewForCell: method. When creating a view for containing two buttons as subviews I really should not have used literal values for the frames. Instead of setting a view for accessoryView property, I rewrote the whole cellForRowAtIndexPath: method and added a subview to the cell's contentView.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"notificationsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
}
PFObject *user = [self.objects objectAtIndex:indexPath.row];
NSString *firstName = [user objectForKey:#"firstName"];
NSString *lastName = [user objectForKey:#"lastName"];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", firstName, lastName];
UIView *view = [UIView new];
view.frame = CGRectMake(230, 2, 80, 40);
view.backgroundColor = [UIColor whiteColor];
UIButton *acceptButton = [UIButton buttonwithType:UIButtonTypeCustom];
UIButton *declineButton = [UIButton buttonWithType:UIButtonTypeCustom];
[acceptButton setTitle:#"" forState:UIControlStateNormal];
[declineButton setTitle:#"" forState:UIControlStateNormal];
[acceptButton setImage:[UIImage imageNamed:#"Ok.png"] forState:UIControlStateNormal];
[declineButton setImage:[UIImage imageNamed:#"Close.png"] forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(acceptButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[declineButton addTarget:self action:#selector(declineButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
acceptButton.frame = CGRectMake(CGRectGetMinX(view.bounds), CGRectGetMinY(view.bounds), CGRectGetWidth(view.bounds)/2, CGRectGetHeight(view.bounds));
declineButton.frame = CGRectMake(CGRectGetMidX(view.bounds), CGRectGetMinY(view.bounds), CGRectGetWidth(view.bounds)/2, CGRectGetHeight(view.bounds));
[view addSubview:acceptButton];
[view addSubview:declineButton];
[cell.contentView addSubview:view];
return cell;
}
The main difference was that when setting the frames for each button, I used literal values (not a good practice) and now I used the CGRect functions CGRectGetMinX(CGRect rect), CGRectGetMinY(CGRect rect), CGRectGetWidth(CGRect rect), CGRectGetMidX(CGRect rect) and CGRectGetHeight(CGRect rect) to get more accurate values for setting each button's frame. This was a misunderstanding of how a UIView's frames work, I recommend always to use these functions to get the origin and size of subviews and not to use literal values.
The problem appeared to be you are not returning the UIView from setAccessoryViewForCell method.
return view;
Please return the view from the mentioned method, it might solve your problem.
Related
I'm trying to implement a table view where all rows have 2 buttons which then do something with the data at the index row they are on.
here is what I have so far:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NotificationCell";
NotificationCell *cell = (NotificationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[NotificationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NotificationObject *notification = nil;
notification = [_notificationArray objectAtIndex:indexPath.row];
cell.profileImage.image = notification.profileImage;
cell.profileImage.layer.cornerRadius = cell.profileImage.frame.size.height /2;
cell.profileImage.layer.masksToBounds = YES;
cell.profileImage.layer.borderWidth = 0;
cell.detailTextView.text = notification.action;
UIButton *denyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
denyButton.frame = CGRectMake(cell.frame.origin.x + 285, cell.frame.origin.y + 20, 23, 23);
[denyButton setBackgroundImage:[UIImage imageNamed:#"DenyRequest.png"] forState:UIControlStateNormal];
[denyButton addTarget:self action:#selector(denyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
denyButton.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:denyButton];
acceptButton.frame = CGRectMake(cell.frame.origin.x + 240, cell.frame.origin.y + 20, 23, 23);
[acceptButton setBackgroundImage:[UIImage imageNamed:#"AcceptRequest.png"] forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(AcceptButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
acceptButton.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:acceptButton];
return cell;
}
-(void)denyButtonPressed:(id)sender{
NSLog(#"buttonPressedDeny");
}
-(void)AcceptButtonPressed:(id)sender{
NSLog(#"buttonPressedAccept");
}
However I am not sure how to find out which index row the selected button was pressed so that I can get the relevant data.
The simplest solution is to assign a tag to each button. For example:
denyButton.tag = 1000 + indexPath.row;
Then on denyButtonPressed:
-(void)denyButtonPressed:(id)sender{
UIButton *b = (UIButton *)sender;
NSInteger row = b.tag - 1000;
NSLog(#"buttonPressedDeny: %d", row);
}
The variable row will hold the index path row where the button was pressed. The addition of 1000 is to avoid collision with other views you may already have.
Let me emphasize that this is the SIMPLEST solution but not the most friendly from a design/architecture point of view.
A more elaborate solution could be to have the buttons as part of NotificationCell, have NotificationCell be the delegate for those buttons, and create a protocol that allows your view controller to be the delegate of each NotificationCell. Then when the button is pressed, it will be handled by NotificationCell, which will pass whatever object is needed to your view controller.
For example, create the following protocol in NotificationCell.h
#protocol NotificationCellDelegate
- (void)denyActionForNotificationObject:(NotificationObject *)notificationObject;
- (void)acceptActionForNotificationObject:(NotificationObject *)notificationObject;
#end
Also add NotificationCell add a property to hold a notification and a delegate:
#property (nonatomic, strong) NotificationObject *notificationObject;
#property (nonatomic, strong) id<NotificationCellDelegate> delegate;
Create a method awakeFromNib (if you are using storyboards)
- (void)awakeFromNib {
[super awakeFromNib];
UIButton *denyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton *acceptButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
denyButton.frame = CGRectMake(self.contentView.frame.origin.x + 285, self.contentView.frame.origin.y + 20, 23, 23);
[denyButton setBackgroundImage:[UIImage imageNamed:#"DenyRequest.png"] forState:UIControlStateNormal];
[denyButton addTarget:self action:#selector(denyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
denyButton.backgroundColor= [UIColor clearColor];
[self.contentView addSubview:denyButton];
acceptButton.frame = CGRectMake(self.contentView.frame.origin.x + 240, self.contentView.frame.origin.y + 20, 23, 23);
[acceptButton setBackgroundImage:[UIImage imageNamed:#"AcceptRequest.png"] forState:UIControlStateNormal];
[acceptButton addTarget:self action:#selector(AcceptButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
acceptButton.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:acceptButton];
}
Implement the selectors you declared:
- (void)denyButtonPressed:(id)sender {
if (_delegate) {
[_delegate denyActionForNotificationObject:_notificationObject];
}
}
- (void)AcceptButtonPressed:(id)sender {
if (_delegate) {
[_delegate acceptActionForNotificationObject:_notificationObject];
}
}
Then in your cellForRowAtIndexPath in your view controller add:
cell.notificationObject = notificationObject;
cell.delegate = self;
Also in your view controller, implement the protocol:
- (void)denyActionForNotificationObject:(NotificationObject *)notificationObject {
// Do something with the notification object
}
- (void)acceptActionForNotificationObject:(NotificationObject *)notificationObject {
// Do something with the notification object
}
I have not tested this in XCode, my apologies if it doesn't compile
Why not work backwards through the view hierarchy and check the button's superview, which should be the content view of the table view cell. Whose superview should be the cell?
-(void)denyButtonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
UIView *contentView = button.superview;
UITableViewCell *cell = contentView.superview;
NSIndexPath * indexPath = self.tableView indexPathForCell:cell];
NSLog(#"row containing button: %d", indexPath.row);
}
i am working with the tableview in which i added 2 buttons on one cell. Below is the code which i used
- (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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
on the tickbtn and crossbtn i am applying following actions :-
-(IBAction)addshed:(UIControl *)sender
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-200 inSection:0];
UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];
UIButton *check1 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+200];
UIButton *check2 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+400];
UIImageView *btnimg1 = [[UIImageView alloc] initWithImage:check1.currentBackgroundImage];
//UIImageView *btnimg2 = [[UIImageView alloc] initWithImage:check2.currentBackgroundImage];
NSLog(#"SHED LIST subviews: %#", btnimg1.image);
// Shed_data *sheddata = [[Shed_data alloc] init];
if (btnimg1.image == [UIImage imageNamed:#"ok_gray.png"]) {
//btnimg.image = [UIImage imageNamed:#"ok_gray.png"];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_green.png"]forState:UIControlStateNormal];
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[self addsheddata:sender];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
}
else if (btnimg1.image == [UIImage imageNamed:#"ok_green.png"])
{
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-red.png"]forState:UIControlStateNormal];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[self removesheddata:sender];
}
}
-(IBAction)removeshed:(UIControl*)sender
{
//.…………………….. My functionality
}
but in both these cases i am getting the tag value of last cell only whenever i am pressing the buttons of the cell.
Please locate my error and help me out to solve it. Your help will be much appreciable.
Try this one as working fine for me. I Just tested with my Xcode 5.
Modification :
1. I Create an NSMutableArray with the name of _objects (_objects = [[NSMutableArray alloc]initWithObjects:#"one",#"two",#"thre", nil];). and give it to my UITableView.
2.Give the tickBtn and crossBtn an different color so easily visible.
3.change the button pressed function to UIControl to UIButton like -(IBAction)addshed:(UIButton *)sender and when button pressed i catch the tag value and print it out on the console.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn setBackgroundColor:[UIColor blackColor]];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[crossbtn setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
-(IBAction)addshed:(UIButton *)sender {
NSLog(#"add shed %d",sender.tag);
}
-(IBAction)removeshed:(UIButton *)sender {
NSLog(#"remove %d",sender.tag);
}
NEW QUESTION UPDATE
Did you try with 10 or more cells and try with some continuous scroll?
And the result is
As the Another Answer says
[cell addSubview:crossbtn];// -------- Change here ---------
Let me clear this as i know about it.
The contentView is a subview of UITableViewCell. please review this reference and here you can see there are actually 3 subviews in a UITableViewCell.
You need to add your button to cell subview not cell's contentview subview. So use this 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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell addSubview:tickbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell addSubview:crossbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
Your code seems fine for cellForRowAtIndexpath:. Error might be in getting the tag value at button click. Try to change with this code:-
-(IBAction)addshed:(UIControl *)sender
{
//.…………………….. My functionality
int selectedRow1 = ((UIControl *)sender).tag;
NSLog(#"No. %d", selectedRow1);
}
I have seen issue. It may be lead to this type of error.
Why do you add subviews again and again to your cell's content view.?
That is, for every cellForRowAtIndexpath: call, button will be add to cell. In case dequeueReusableCellWithIdentifier:, your last cell may reuse to any other cell while scroll. It will lead to your error. that is your cell will contain two button.(tag with last cell and tag with your current cell).
In this line [cell.contentView addSubview:tickbtn];, you have to do some change according to add once and also for crossbtn.
Updation: I have seen your updated question. My suggestion, better use custom cell. Use this link to how to create custom cell.. Lot of confusion in your code. ex. in this line UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];, It will give unexpected. Don't call delegate method like this.
I use custom cell on UITableView using QuickDialog
In this custom cell I have several UILabel, UIImageView and a button which has the cell size and display on the top of the others subviews.
I want this button handle touch envent and call a selector. But even though the button is at the top position, the touch event does not trigger when I touch a subview.
- (UITableViewCell *)getCellForTableView:(QuickDialogTableView *)tableView controller:(QuickDialogController *)controller
{
UITableViewCell *cell = [super getCellForTableView:tableView controller:controller];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = cell.frame;
[btn setEnabled:YES];
[btn setExclusiveTouch:YES];
[btn setBackgroundColor:[UIColor blueColor]]; // To check if the button is at the top position
[btn setStringTag:labelIdText];
[btn addTarget:self action:#selector(handleTap:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:label1];
[cell addSubview:label2];
[cell addSubview:image1];
[cell addSubview:image2];
[cell addSubview:btn];
cell.userInteractionEnabled = YES;
return cell;
}
The selector :
- (IBAction)handleTap:(id)sender
{
NSLog(#"CELL TAPPED : \n");
}
Thanks a lot.
EDIT :
New version of the code :
- (UITableViewCell *)getCellForTableView:(QuickDialogTableView *)tableView controller:(QuickDialogController *)controller
{
UITableViewCell *cell = [super getCellForTableView:tableView controller:controller];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *top = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleSingleTap:)];
[top setStringTag:labelIdText];
[top addGestureRecognizer:singleFingerTap];
[cell.contentView addSubview:label_1];
[cell.contentView addSubview:label_2];
[cell.contentView addSubview:image_1];
[cell.contentView addSubview:image_2];
[cell.contentView addSubview:top];
cell.userInteractionEnabled = YES;
image_1.userInteractionEnabled = YES;
image_2.userInteractionEnabled = YES;
return cell;
}
The selector :
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
NSLog(#"CELL TAPPED : \n");
}
The event is handle when I touch the text containing in the UILabel.
But it's still don't work with the UIImageView despite userInteractionEnabled setted to YES for the images.
Thanks again.
It seams you are assigning to the button the cell frame and then add it to the cell itself. In this way the position of the button is not the one you expect, and even though you can see the button it will not respond to touch because it resides outside the cell bounds.
Try to change this:
btn.frame = cell.frame;
to this:
btn.frame = cell.bounds;
Also when working with UItableViewCell remember to add subviews to its contentView and not the cell itself:
[cell.contentView addSubview:aCustomView];
I'm a newbie. I am using this code to create a UITableViewCell but when I reload the table the button's image is not always correct, although all labels work fine. I don't know why. How can I fix this issue?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UILabel *FileNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
FileNameLabel.tag = 1000;
FileNameLabel.backgroundColor = [UIColor clearColor];
FileNameLabel.font = [UIFont fontWithName:#"Helvetica" size:16];
FileNameLabel.font = [UIFont boldSystemFontOfSize:16];
FileNameLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview: FileNameLabel];
[FileNameLabel release];
UILabel *UploadTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 150, 25)];
UploadTimeLabel.tag = 2000;
UploadTimeLabel.backgroundColor = [UIColor clearColor];
UploadTimeLabel.font = [UIFont fontWithName:#"Helvetica" size:12];
UploadTimeLabel.textColor = [UIColor grayColor];
[cell.contentView addSubview: UploadTimeLabel];
[UploadTimeLabel release];
UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 30)];
pricelabel.backgroundColor = [UIColor clearColor];
pricelabel.font = [UIFont fontWithName:#"Helvetica" size:16];
pricelabel.font = [UIFont boldSystemFontOfSize:16];
pricelabel.textColor = [UIColor darkGrayColor];
pricelabel.tag = 3000;
//pricelabel.hidden = YES;
pricelabel.textAlignment = NSTextAlignmentRight;
[cell.contentView addSubview: pricelabel];
[pricelabel release];
market = [[UIButton alloc] init];;
[market setFrame:CGRectMake(200, 6, 30, 30)];
market.tag = 4000;
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:market];
}
if( [temp count] > 0)
{
UILabel *fileNameLbl = (UILabel*)[cell.contentView viewWithTag:1000];
fileNameLbl.text =[temp objectAtIndex:indexPath.row];
UILabel *uploadlbl = (UILabel*)[cell.contentView viewWithTag:2000];
uploadlbl.text =[UploadTimeAllArr objectAtIndex:indexPath.row];
}
UIButton *marketButton = (UIButton*)[cell.contentView viewWithTag:4000];
[marketButton setTag:indexPath.row];
if([sellingArray count]>0)
{
NSLog(#"sellingArray %#",sellingArray);
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]) // nothing
{
[marketButton setSelected:NO];
[marketButton setImage:[UIImage imageNamed:#"Marketplace.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
else if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"2"]) // marketplace
{
[marketButton setSelected:YES];
[marketButton setImage:[UIImage imageNamed:#"MarketplaceSelect.png"] forState:UIControlStateNormal];
marketButton.enabled = YES;
}
}
return cell;
}
Your main problem here is that you are recreating new views in your cell every time this method is called. You want to create all reusable elements inside the if(cell == nil) otherwise it will make duplicates. Anything that is dynamic must be created outside of this. I took your code and modified it. This should work better.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// Everything that does not change should go in here!
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UILabel *pricelabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 80, 30)];
pricelabel.backgroundColor = [UIColor clearColor];
pricelabel.font = [UIFont fontWithName:#"Helvetica" size:16];
pricelabel.font = [UIFont boldSystemFontOfSize:16];
pricelabel.textColor = [UIColor darkGrayColor];
pricelabel.tag = 3000;
//pricelabel.hidden = YES;
pricelabel.textAlignment = NSTextAlignmentRight;
[cell addSubview:pricelabel];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:market];
}
// find market button, since we could be reusing a cell we cannot rely on a tag
// value to find it. (This would only work with one button though).
UIButton *market;
for (UIView *subview in cell.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
market = (UIButton *)subview;
break;
}
}
// set all defaults in case of reuse
[market setImage:[UIImage imageNamed:#"DefaultImage.png"] forState:UIControlStateNormal];
market.selected = YES;
market.enabled = NO;
market.clearsContextBeforeDrawing = NO;
if([sellingArray count] > 0) {
NSLog(#"sellingArray %#",sellingArray);
if([[sellingArray objectAtIndex:indexPath.row] isEqualToString:#"0"]) {
// not sure if this is supposed to be YES or NO
market.clearsContextBeforeDrawing = YES;
[market setSelected:NO];
[market setImage:[UIImage imageNamed:#"Marketplace.png"] forState:UIControlStateNormal];
market.enabled = YES;
}
}
[market setTag:indexPath.row];
return cell;
}
Since it appears you are not using ARC, make sure you look over this code for any needed reference counting.
dequeReusablecellWithIdentifier: method get return the cell instance already created available,If the reference points still to nil ,we need a valid cell and create one cell to return from that cellForRowatIndexpath: method.That is what being checked in the (cell ==nil).When you create a new cell it is creation and hence all settings custom and all has to be done here.
Second Edit:
This was copied from an answer above:
inside the -cellForRowAtIndexPath: method:
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSubtitle];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:market];
//Add all your UILabel INITIATION stuff here as well
}
UIButton *marketButton;
for (UIView *subview in cell.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
marketButton = (UIButton *)subview;
break;
}
}
marketButton.tag = [indexPath row];
UILabel *priceLabel = [cell.contentView viewWithTag:3000];
UILabel *uploadTimeLabel = [cell.contentView viewWithTag:2000];
//Set up your labels and button now
return cell;
}
EDIT: Leaving my original answer below for posterity but I see that you are setting the table index row as the MarketButton's tag. If you're using that to figure out which dataSource object to query, this is bad practice. You should be making a custom cell which can hold a reference to the object in your data source, so you don't have to ask the button for its tag, and then ask the data source array for the object at index:tag.
The reason this is bad is because somewhere, the state of your array could change, but the table cell is still displayed and still holds a tag pointing at the wrong index. If you just have the cell keep track of the object in question, no matter what happens to the array structure you're guaranteed to be modifying the object you need to.
The only thing I would change about Firo's answer is to just add a "tag" property to each view in the cell, so you don't have to iterate each time you want to find it.
Also took out the [[UIButton alloc]init] line because it's superfluous and might be considered a dangling pointer.
if (cell == nil) {
// Everything that does not change should go in here!
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UIButton *market = [UIButton buttonWithType:UIButtonTypeCustom];
[market setFrame:CGRectMake(200, 6, 30, 30)];
[market addTarget:self action:#selector(marketPressedAction:) forControlEvents:UIControlEventTouchDown];
market.tag = 9999;
[cell.contentView addSubview:market];
}
//don't have to do UIView iteration here
UIButton *marketButton = [cell.contentView viewWithTag:9999];
I've tried a bunch of stuff - adding a button from the object browser, changing attributes, searching the web, but no luck. Essentially, I'd like to do --in the storyboard--:
where you see "add to contacts" "share location" and "add to bookmarks".
You should create a UITableViewCell whose contentView holds 3 separate UIButtons.
To do this programmatically, in your tableView:cellForRowAtIndexPath: data source method, you can use code similar to the following:
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* identifier = #"cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.backgroundColor = [UIColor clearColor];
UIButton* button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton* button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
UIButton* button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.frame = UIEdgeInsetsInsetRect(cell.contentView.bounds, UIEdgeInsetsMake(0, 0, 0, 250));
button2.frame = UIEdgeInsetsInsetRect(cell.contentView.bounds, UIEdgeInsetsMake(0, 125, 0, 125));
button3.frame = UIEdgeInsetsInsetRect(cell.contentView.bounds, UIEdgeInsetsMake(0, 250, 0, 0));
button1.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
button2.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
button3.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[cell.contentView addSubview:button1];
[cell.contentView addSubview:button2];
[cell.contentView addSubview:button3];
}
return cell;
}
Also, in the tableView:willDisplayCell: method of your delegate, do the following to have the default decoration of the cell totally disappear:
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundView = nil;
}
You should obtain a result very similar to what you posted.
Put the three buttons in a UIView that is 320 pixels wide and say 60 hight, and make that view the footer of your table.
The UITableView is styled using the UITableViewStyleGrouped stye.
The three UIButtons are programmatically added to the tableView.tableFooterView.
Alternatively, you can add three UIButtons to the contentView of the last cell.
Add buttons like:
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
theButton.frame = CGRectMake(20, 20, 200, 40);
[theButton setTitle:#"Button" forState:UIControlStateNormal];
[theButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:theButton];
Get the button positions correctly using trial and error :)