2012-09-24 57 views
5

Estoy agregando un botón en la celda de vista de tabla dinámicamente. Botón que se muestra en la tabla, pero no puedo hacer clic en ellos. Aquí está mi código,¿Cómo agregar un botón que se puede hacer clic en la celda de la tabla?

Este código de mi clase tableviewcell:

MessageTableViewCell.h

#import <UIKit/UIKit.h> 
@interface MessageTableViewCell : UITableViewCell { 
{IBOutlet UIButton *chat_pic_btn;}} 
@property (nonatomic, retain) UIButton *chat_pic_btn; 
@end; 

MessageTableViewCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {chat_pic_btn=[[UIButton alloc]init]; 
[self.contentView addSubview:chat_pic_btn];}} 

MessageTable.m

-(void)customActionPressed :(id)sender 
{ 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Custom Button Pressed" 
                 message:[NSString stringWithFormat: @"You pressed the custom button on cell"] 
                 delegate:self cancelButtonTitle:@"Great" 
               otherButtonTitles:nil]; 
    [alertView show]; 
} 

- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"CellIdentifier"; 
    MessageTableViewCell *cell = (MessageTableViewCell *)[myTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     // cell = [[MessageTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]; 
     cell = [[MessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
cell.chat_pic_btn.frame = CGRectMake(180, 24, 70,35); 
      [cell.chat_pic_btn setImage:[UIImage imageNamed:@"done.png"]forState:UIControlStateNormal]; 
      [cell.chat_pic_btn addTarget:self action:@selector(customActionPressed:) forControlEvents:UIControlEventTouchDown]; 
return cell; 
} 

Súplica ayúdame. Gracias.

+0

¿Es este botón en todas las vistas? ¿Se procesa correctamente? – ThomasW

+0

Ya hay una condición si la condición es verdadera, entonces el botón se mostrará en la vista. El botón se muestra correctamente, pero no puedo llamar a un método al hacer clic. – Saurabh

+0

Probablemente también deba mostrar el código que usa para crear las celdas de la tabla. Además, ¿qué sucede cuando haces clic en la celda del botón? Hay un choque? O sin efecto? – ThomasW

Respuesta

10

Sugiero eliminas la salida de tu Botón en TableViewCell. y acaba de crear su botón de forma dinámica en cellForRowAtIndexPath: creé una clase SampleCell, subclase de UITableViewCell, que tiene una salida de UILabel llamé "LBL." Esto debería funcionar en su código, en el supuesto de que el selector está en la misma clase donde pones tu tablview;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"SampleCell"; 
    SampleCell *cell = (SampleCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SampleCell" owner:self options:nil]; 
     for (id currentObject in topLevelObjects) { 
      if ([currentObject isKindOfClass:[UITableViewCell class]]) { 
       cell = (SampleCell *)currentObject; 
       break; 
      } 
     } 
    } 
    // Configure the cell. 
    cell.lbl.text = @"Hello"; 
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

    //set the position of the button 
    button.frame = CGRectMake(cell.frame.origin.x + 100, cell.frame.origin.y + 20, 100, 30); 
    [button setTitle:@"World" forState:UIControlStateNormal]; 
    [button addTarget:self action:@selector(customActionPressed:) forControlEvents:UIControlEventTouchUpInside]; 
    button.backgroundColor= [UIColor clearColor]; 
    [cell.contentView addSubview:button]; 

    return cell; 
} 
+2

Gracias por su respuesta. Pero aún así no está funcionando. :( – Saurabh

+0

hmm extraño ... Hace un tiempo lo codifiqué ... ¿eliminó su IBOutlet UIButton * btn en su Clase TableViewCell? –

+0

Use cell.bounds.origin, no cell.frame.origin para el marco del botón. –

1
UIButton *yourBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0, 50, 50)]; 
[yourBtn setImage:[UIImage imageNamed:@"yourImage.png"] forState:UIControlStateNormal]; 
[yourBtn addTarget:self action:@selector(submitBtnPress:) forControlEvents:UIControlEventTouchUpInside]; 

cell.accessoryView = yourBtn; 
+0

lo siento, es mi error cuando publico una pregunta. Pero no está funcionando ... y la línea de código que usted proporciona tampoco funciona. Este es mi método que he llamado - (IBAction) show_chat_pic: (id) {emisor NSLog (@ "en el espectáculo"); UIImageView * imageview = [[UIImageView alloc] initWithFrame: CGRectMake (5, 50, 310, 320)]; imageview.image = sender_profile2; [self.view addSubview: imageview]; } – Saurabh

+2

No es una respuesta .... Hay que comentar ... – Maulik

+0

chk respuesta actualizada @ user1652551 – Rajneesh071

0

No ha dado ningún evento de control al botón o Cambiar a UIControlEventTouchUpInside de UIControlStateNormal y hacerlo de una sola vez :)

+0

Creo que he dado el caso [cell.chat_pic_btn addTarget: acción de auto: @selector (show_chat_pic :) forControlEvents: UIControlEventTouchUpInside]; – Saurabh

+0

Verifique este enlace e intente y modifique su código http: // stackoverflow.com/questions/10732229/uibutton-not-respondding-to-click-event-in-uitableviewcell – IronManGill

5

Asegúrese de ajustar UserInteraction a SÍ en vista celular y su botón de

self.userInteractionEnabled = YES; 
Cuestiones relacionadas