iPhone-在UITableView的选定行中添加按钮

问题描述

| 我正在使用XCode的基于导航的应用程序模板来创建以UITableView为中心的应用程序。 当用户在UITableView中选择一行时,我想在该所选单元格内显示一个按钮。我只想在选定的单元格中显示此按钮,而不要在其他任何单元格中显示。如果用户此后选择其他单元格,也会发生同样的情况。 我该怎么做呢?可能吗?     

解决方法

子类化UITableViewCell并向其中添加按钮。
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        [button setFrame:CGRectMake(320.0 - 90.0,6.0,80.0,30.0)]; 
        [button setTitle:@\"Done\" forState:UIControlStateNormal];
        button.hidden = YES;
        [self.contentView addSubview:button];
    }
    return self;
}
然后像这样覆盖setSelected:
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    self.button.hidden = !selected;
}
    ,使用以下类似的方法应该可以实现:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (lastClickedCell != nil) {
        // need to remove button from contentView;
        NSArray *subviews = lastClickedCell.contentView.subviews;
        for (UIButton *button in subviews) {
            [button removeFromSuperview];
        }
    }
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // this gives you a reference to the cell you wish to change;
    UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; // you can change the type to whatever you want
    [cellButton setFrame:CGRectMake(x,y,w,h)]; // you will need to set the x,h values to what you want
    // if you want the button to do something,you will need the next line;
    [cellButton addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchUpInside];
    // now you will need to place the button in your cell;
    [cell.contentView addSubview:cellButton];
    [tableView reloadData];  // this updates the table view so it shows the button;
    lastClickedCell = cell;  // keeps track of the cell to remove the button later;
}
编辑:当您选择新的单元格时,您当然需要从contentView中删除按钮,因此您将需要一些逻辑。子类化可能是一个更简单的解决方案,但是如果您不想对子类化,这将是您需要采取的路线。例如,您想在标头中声明以下内容。
UITableViewCell *lastClickedCell;
然后,您将希望将其合并到上面(我将对其进行更改以放入其中);     ,您是否在developer.apple.com上查看了UITableViewController和UIButton的文档?     ,这是一个简单的解决方案! 在诸如viewDidLoad函数之类的地方创建按钮(确保在.h文件中声明了它,以便可以从任何地方引用它) 在-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath中 添加以下内容:
  if (yourButton)
            [yourButton removeFromSuperview];

        [[tableView cellForRowAtIndexPath:indexPath] addSubview:yourButton];
        [yourButton setSelected:NO]; 
        [yourButton setHighlighted:NO];