在按钮单击外部类时,将tableView添加为子视图

时间:2014-01-02 21:12:41

标签: ios objective-c uitableview

我有tableViewController个自定义单元格。代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
    if (indexPath.section < 1) {
        static NSString *adicionaCellIdentifier = @"AdicionaCell";
        AtividadesPraticadasCustomCell *adicionaCell = [tableView dequeueReusableCellWithIdentifier:adicionaCellIdentifier];
        if (!adicionaCell)
        {
            adicionaCell = [[AtividadesPraticadasCustomCell alloc]     initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AdicionaCell"];
        }
        adicionaCell.backgroundColor = [UIColor blackColor];
        adicionaCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSLog(@"CELL1");
        return adicionaCell;
    }

    else {
        static NSString *atividadesCellIdentifier = @"AtividadesCell";
        UITableViewCell *atividadesPraticadasCell = [tableView dequeueReusableCellWithIdentifier:atividadesCellIdentifier];
        if (!atividadesPraticadasCell) {
            atividadesPraticadasCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AtividadesCell"];
        }
        NSLog(@"%lu", (unsigned long)_arrayAtividadesPraticadas.count);
        atividadesPraticadasCell.textLabel.text = [_arrayAtividadesPraticadas objectAtIndex:indexPath.row];
        NSLog(@"CELL2");


        return atividadesPraticadasCell;
    }


}

在第一个单元格中,我有UIButton,但它是在我为这些单元格创建的UITableViewCell类中声明的。

我还为我想要添加为tableView的子视图的tableViewController创建了一个类。

现在,当我使用下面的代码打开subView时,它不起作用。此代码位于用于我的自定义单元格的UITableViewCell类中。

- (IBAction)botaoAdicionar:(id)sender {
    NSLog(@"TESTE BOTAO ADICIONAR");
    AtividadesPraticadasTableView *tableview = [[AtividadesPraticadasTableView alloc] initWithFrame:CGRectMake(10, 10, 300, 300) style:UITableViewStylePlain];
    Cadastro3TableViewController *teste = [[Cadastro3TableViewController alloc] init];
    [teste.view addSubview:tableview];

}

当我使用tableViewController的ViewDidLoaddidSelectRowAtIndexPath中的代码时,它工作正常。

我还试图在mainViewController中创建一个方法并从UIButton调用该方法,但它也没有用。当我在didSelectRowAtIndexPath调用该方法时,它可以工作。我不确定我错过了什么。

方法如下:

 - (void)abrirTableViewParaAtividadesPraticadas
 {
     AtividadesPraticadasTableView *tableview = [[AtividadesPraticadasTableView alloc] initWithFrame:CGRectMake(10, 10, 300, 300) style:UITableViewStylePlain];
     [self.view addSubview:tableview];
 }

1 个答案:

答案 0 :(得分:1)

在此处添加按钮目标:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
     //init your custom cell here
     [yourCustomCell.button addTarget:self action:@selector(botaoAdicionar:) forControlEvents:UIControlEventTouchUpInside];
}

然后在-(IBAction)botaoAdicionar:(id)sender中实施UITableViewController方法。

此外,如果您想要添加UIViewControllerUITableViewController作为子视图,您必须这样做:

[destinationVC.view addSubview:tableViewController.view];
相关问题