我在Tableview的所有单元格中显示按钮时遇到问题。
这是我的代码:
- (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;
}
我遇到的问题是按钮只显示在顶部单元格中。
道歉,如果这是一个简单的错误,对目标c仍然相对较新!
答案 0 :(得分:1)
您正在将按钮添加到单元格的内容视图中,因此按钮的框架不应考虑单元格的框架(您传递的值相对于单元格的框架,而不是绝对值)。因此,框架设置应如下所示,
denyButton.frame = CGRectMake(285, 20, 23, 23);
acceptButton.frame = CGRectMake(240, 20, 23, 23);
你还有另一个问题。当您滚动并重复使用单元格时,您将向已经有按钮的单元格添加按钮。所以,你需要输入一个if-else子句来检查你是否已经在单元格中有按钮,或者在添加新按钮之前删除按钮(个人而言,我只是在故事板中创建单元格,而不是必须首先使用所有这些代码。)