Reputation: 183
I'm having a problem displaying buttons in all cells of Tableview.
Here is my code:
- (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];
denyButton.tag = 1000 + indexPath.row;
[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];
acceptButton.tag = 1000 + indexPath.row;
[cell.contentView addSubview:acceptButton];
return cell;
}
The problem I'm having is that the buttons are only displayed in the top cell.
Apologies if this is a simple mistake, still relatively new to objective c!
Upvotes: 0
Views: 36
Reputation: 104082
You're adding the buttons to the cell's content view, so the frame for your buttons shouldn't take into account the cell's frame (the values you pass are relative to the cell's frame, not absolute values). So, the frame setting should look like this,
denyButton.frame = CGRectMake(285, 20, 23, 23);
acceptButton.frame = CGRectMake(240, 20, 23, 23);
You have another problem also. When you scroll, and the cells are reused, you will be adding buttons to cells that already have buttons. So, you either need to put in an if-else clause that checks to see if you have buttons in the cell already, or remove the buttons, before adding new ones (personally, I would just make the cell in the storyboard, and not have to use all this code in the first place).
Upvotes: 1